A dictionary in Python is a collection of key-value pairs.

  1. alien = {}
  2. alien['color'] = 'green' # 新增
  3. alien['speed'] = 'fast'
  4. alien[5] = 'hello' # 可以是数字
  5. alien['color'] = 'red' # 修改
  6. del alien['speed'] # 删除
  7. print(alien)

用[]访问字典值,如果不存在则会报错,可以用get()方法,第一个参数为要获取的键,第二个参数为键值不存在时返回的默认值,如果不给第二个参数,返回None

  1. polls = {
  2. 'Lily': 'Python',
  3. 'Judy': 'Java',
  4. 'cathy': 'JS',
  5. }
  6. poll = polls.get('andy', 'not found')
  7. print(poll)

loop through a dictionary

  1. polls = {
  2. 'lily': 'Python',
  3. 'judy': 'Java',
  4. 'cathy': 'JS',
  5. 'andy': 'Python',
  6. 'caven': 'C',
  7. }
  8. # 遍历键值对
  9. for key,value in polls.items():
  10. print(f"{key}'s favorite language is {value}")
  11. # 只遍历key, keys()得到由key组成的数组
  12. for key in polls.keys():
  13. print(key)
  14. # key排序
  15. for key in sorted(polls.keys()):
  16. print(key)
  17. # 与上面等价,默认是遍历key
  18. for key in polls:
  19. print(key)
  20. # 遍历值
  21. for value in polls.values():
  22. print(value)
  23. # value去重, set不允许存储重复值
  24. for value in set(polls.values()):
  25. print(value)
  26. # 声明一个set
  27. a_set = {'cat', 'dog', 'cow', 'horse'}