dict_basics.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """dict_basics.py - Python 字典基础示例
  2. 包含常见的字典操作示例:创建、访问、添加、修改、删除、遍历、嵌套和推导式等。
  3. 运行后会打印每个示例的结果,并在代码中注释预期输出。
  4. """
  5. def main():
  6. # 1. 创建字典
  7. student = {"name": "Tom", "age": 18, "city": "Beijing"}
  8. print("student ->", student)
  9. # 2. 访问值
  10. print("student['name'] ->", student["name"]) # Tom
  11. print("student['age'] ->", student["age"]) # 18
  12. # 3. 安全获取值
  13. print("student.get('score') ->", student.get("score")) # None
  14. print("student.get('score', 0) ->", student.get("score", 0)) # 0
  15. # 4. 添加和修改
  16. student["score"] = 95
  17. student["age"] = 19
  18. print("after add/modify ->", student)
  19. # 5. 删除键值对
  20. del student["city"]
  21. print("after del student['city'] ->", student)
  22. # pop() 删除指定键并返回值
  23. age = student.pop("age")
  24. print("age popped ->", age)
  25. print("after pop('age') ->", student)
  26. # 6. 判断 key 是否存在
  27. print("'name' in student ->", "name" in student) # True
  28. print("'score' in student ->", "score" in student) # True
  29. print("'city' in student ->", "city" in student) # False
  30. # 7. 遍历字典
  31. for key in student:
  32. print("loop key ->", key)
  33. for key, value in student.items():
  34. print("loop item ->", key, value)
  35. for value in student.values():
  36. print("loop value ->", value)
  37. # 8. 常见方法
  38. print("student.keys() ->", student.keys())
  39. print("student.values() ->", student.values())
  40. print("student.items() ->", student.items())
  41. print("len(student) ->", len(student))
  42. # 9. 字典嵌套
  43. users = {
  44. "alice": {"age": 20, "city": "Shanghai"},
  45. "bob": {"age": 22, "city": "Hangzhou"}
  46. }
  47. print("users['alice']['city'] ->", users["alice"]["city"]) # Shanghai
  48. # 10. 字典推导式
  49. squares = {x: x * x for x in range(1, 5)}
  50. print("squares ->", squares) # {1: 1, 2: 4, 3: 9, 4: 16}
  51. # 11. 统计频次
  52. counts = {"apple": 3, "banana": 2}
  53. counts["apple"] += 1
  54. print("counts ->", counts)
  55. # 12. 说明:
  56. # - 键唯一
  57. # - 通过 key 快速查找 value
  58. # - 适合表达“映射关系”
  59. # - Python 3.7+ 保留插入顺序
  60. if __name__ == '__main__':
  61. main()