字典

一.一个简单的字典

  1. alien_0 = {'color': 'green', 'points': 5}
  2. print(alien_0['color'])
  3. print(alien_0['points'])
  1. green
  2. 5

二.使用字典

在Python中,字典是一系列键—值对。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。
键—值对是两个相关联的值。指定键时,Python将返回与之相关联的值。键和值之间用冒号分隔,而键—值对之间用逗号分隔。在字典中,你想存储多少个键—值对都可以。 最简单的字典只有一个键—值对。

1.访问字典中的值

  1. alien_0 = {'color': 'green'}
  2. print(alien_0['color'])
  1. green

2.添加键值对

  1. alien_0 = {'color': 'green', 'points': 5}
  2. print(alien_0)
  3. alien_0['x_position'] = 0
  4. alien_0['y_position'] = 25
  5. print(alien_0)
  1. {'color': 'green', 'points': 5}
  2. {'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

3.先创建一个空字典

  1. alien_0 = {}
  2. alien_0['color'] = 'green'
  3. alien_0['points'] = 5
  4. print(alien_0)
  1. {'color': 'green', 'points': 5}

4.修改字典中的值

  1. alien_0 = {'color': 'green'}
  2. print("The alien is " + alien_0['color'] + ".")
  3. alien_0['color'] = 'yellow'
  4. print("The alien is now " + alien_0['color'] + ".")
  1. The alien is green.
  2. The alien is now yellow.

5.删除键值对

  1. alien_0 = {'color': 'green', 'points': 5}
  2. print(alien_0)
  3. del alien_0['points']
  4. print(alien_0)
  1. {'color': 'green', 'points': 5}
  2. {'color': 'green'}

三.遍历字典

1.遍历所有键值对

  1. user_0 = {
  2. 'username': 'efermi',
  3. 'first': 'enrico',
  4. 'last': 'fermi',
  5. }
  6. for key, value in user_0.items():
  7. print("\nKey: " + key)
  8. print("Value: " + value)
  1. Key: last
  2. Value: fermi
  3. Key: first
  4. Value: enrico
  5. Key: username
  6. Value: efermi

2.遍历字典中的所有键

  1. favorite_languages = {
  2. 'jen': 'python',
  3. 'sarah': 'c',
  4. 'edward': 'ruby',
  5. 'phil': 'python',
  6. }
  7. for name in favorite_languages.keys():
  8. print(name.title())
  1. Jen
  2. Sarah
  3. Phil
  4. Edward

3.按顺序遍历字典中的所有键

  1. favorite_languages = {
  2. 'jen': 'python',
  3. 'sarah': 'c',
  4. 'edward': 'ruby',
  5. 'phil': 'python',
  6. }
  7. for name in sorted(favorite_languages.keys()):
  8. print(name.title() + ", thank you for taking the poll.")
  1. Edward, thank you for taking the poll.
  2. Jen, thank you for taking the poll.
  3. Phil, thank you for taking the poll.
  4. Sarah, thank you for taking the poll.

4.遍历字典中的所有值

  1. favorite_languages = {
  2. 'jen': 'python',
  3. 'sarah': 'c',
  4. 'edward': 'ruby',
  5. 'phil': 'python',
  6. }
  7. print("The following languages have been mentioned:")
  8. for language in favorite_languages.values():
  9. print(language.title())
  1. The following languages have been mentioned:
  2. Python
  3. C
  4. Python
  5. Ruby

这种做法提取字典中所有的值,而没有考虑是否重复。涉及的值很少时,这也许不是问题,但如果被调查者很多,最终的列表可能包含大量的重复项。为剔除重复项,可使用集合(set)。集合类似于列表,但每个元素都必须是独一无二的:

  1. favorite_languages = {
  2. 'jen': 'python',
  3. 'sarah': 'c',
  4. 'edward': 'ruby',
  5. 'phil': 'python',
  6. }
  7. print("The following languages have been mentioned:")
  8. for language in set(favorite_languages.values()):
  9. print(language.title())
  1. The following languages have been mentioned:
  2. Python
  3. C
  4. Ruby

四.嵌套

1.字典列表

  1. alien_0 = {'color': 'green', 'points': 5}
  2. alien_1 = {'color': 'yellow', 'points': 10}
  3. alien_2 = {'color': 'red', 'points': 15}
  4. aliens = [alien_0, alien_1, alien_2]
  5. for alien in aliens:
  6. print(alien)
  1. {'color': 'green', 'points': 5}
  2. {'color': 'yellow', 'points': 10}
  3. {'color': 'red', 'points': 15}

2.在字典中存储列表

  1. # 存储所点比萨的信息
  2. pizza = {
  3. 'crust': 'thick',
  4. 'toppings': ['mushrooms', 'extra cheese'],
  5. }
  6. # 概述所点的比萨
  7. print("You ordered a " + pizza['crust'] + "-crust pizza " +
  8. "with the following toppings:")
  9. for topping in pizza['toppings']:
  10. print("\t" + topping)
  1. You ordered a thick-crust pizza with the following toppings:
  2. mushrooms
  3. extra cheese

3.在字典中存储字典

  1. users = {
  2. 'aeinstein': {
  3. 'first': 'albert',
  4. 'last': 'einstein',
  5. 'location': 'princeton',
  6. },
  7. 'mcurie': {
  8. 'first': 'marie',
  9. 'last': 'curie',
  10. 'location': 'paris',
  11. },
  12. }
  13. for username, user_info in users.items():
  14. print("\nUsername: " + username)
  15. full_name = user_info['first'] + " " + user_info['last']
  16. location = user_info['location']
  17. print("\tFull name: " + full_name.title())
  18. print("\tLocation: " + location.title()
  1. Username: aeinstein
  2. Full name: Albert Einstein
  3. Location: Princeton
  4. Username: mcurie
  5. Full name: Marie Curie
  6. Location: Paris