当前位置:   article > 正文

《Python编程:从入门到实践》读书笔记:第6章 字典_【美】 eric matthes 著《 python 编程——从入门到实践》第六章。

【美】 eric matthes 著《 python 编程——从入门到实践》第六章。

目录

第6章 字典

6.1 一个简单的字典

6.2 使用字典

6.2.1 访问字典中的值

6.2.2 添加键值对

6.2.3 先创建一个空字典

6.2.4 修改字典中的值

6.2.5 删除键值对

6.2.6 由类似对象组成的字典

6.2.7 使用get()来访问值

6.3 遍历字典

6.3.1 遍历所有键值对

6.3.2 遍历字典中的所有键

6.3.3 按特定顺序遍历字典中的所有键

6.3.4 遍历字典中的所有值

6.4 嵌套

6.4.1 字典列表

6.4.2 在字典中存储列表

6.4.3 在字典中存储字典


第6章 字典

6.1 一个简单的字典

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

6.2 使用字典

在Python中,字典是一系列键值对。每个键都与一个值相关联,你可使用键来访问相关联的值。

6.2.1 访问字典中的值

  1. alien_0 = {'color': 'green', 'points': 5}
  2. new_points = alien_0['points']
  3. print(f'You just earned {new_points} points!')
You just earned 5 points!

6.2.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, 'x_position': 0, 'y_position': 25}

6.2.3 先创建一个空字典

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

6.2.4 修改字典中的值

  1. alien_0 = {}
  2. alien_0['color'] = 'green'
  3. alien_0['points'] = 5
  4. print(alien_0)
  5. print(f"The alien is {alien_0['color']}.")
  6. alien_0['color'] = 'yellow'
  7. print(f"The alien is now {alien_0['color']}.")
  1. {'color': 'green', 'points': 5}
  2. The alien is green.
  3. The alien is now yellow.
  1. alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
  2. print(f"Original position: {alien_0['x_position']}")
  3. # 向右移动外星人。
  4. # 根据当前速度确定将外星人向右移动多远。
  5. if alien_0['speed'] == 'slow':
  6. x_increment = 1
  7. elif alien_0['speed'] == 'medium':
  8. x_increment = 2
  9. else:
  10. x_increment = 3
  11. # 新位置为旧位置加上移动距离
  12. alien_0['x_position'] = alien_0['x_position'] + x_increment
  13. print(f"New position: {alien_0['x_position']}")
  1. Original position: 0
  2. New position: 2

6.2.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'}

删除的键值对会永远消失。

6.2.6 由类似对象组成的字典

  1. favorite_language = {
  2. 'jen': 'python',
  3. 'sarah': 'c',
  4. 'edward': 'ruby',
  5. 'phil': 'python',
  6. }
  7. language = favorite_language['sarah'].title()
  8. print(f"Sarah's favorite language is {language}.")
Sarah's favorite language is C.

6.2.7 使用get()来访问值

  1. alien_0 = {'color': 'green', 'speed': 'slow'}
  2. print(alien_0['points'])
  1. print(alien_0['points'])
  2. KeyError: 'points'
  1. alien_0 = {'color': 'green', 'speed': 'slow'}
  2. point_value = alien_0.get('points', 'No point value assigned.')
  3. print(point_value)
No point value assigned.

6.3 遍历字典

字典可用于以各种方式存储信息,因此有多种遍历方式:可遍历字典的所有键值对,也可仅遍历键或值。

6.3.1 遍历所有键值对

  1. user_0 = {
  2. 'username': 'efermi',
  3. 'first': 'enrico',
  4. 'last': 'fermi',
  5. }
  6. for key, value in user_0.items():
  7. print(f"\nKey: {key}")
  8. print(f"Value: {value}")
  1. Key: username
  2. Value: efermi
  3. Key: first
  4. Value: enrico
  5. Key: last
  6. Value: fermi
  1. favorite_language = {
  2. 'jen': 'python',
  3. 'sarah': 'c',
  4. 'edward': 'ruby',
  5. 'phil': 'python',
  6. }
  7. for name, language in favorite_language.items():
  8. print(f"{name.title()}'s favorite language is {language.title()}")
  1. Jen's favorite language is Python
  2. Sarah's favorite language is C
  3. Edward's favorite language is Ruby
  4. Phil's favorite language is Python

6.3.2 遍历字典中的所有键

  1. favorite_language = {
  2. 'jen': 'python',
  3. 'sarah': 'c',
  4. 'edward': 'ruby',
  5. 'phil': 'python',
  6. }
  7. for name in favorite_language.keys():
  8. print(name.title())
  9. print('\n')
  10. for name in favorite_language:
  11. print(name.title())
  1. Jen
  2. Sarah
  3. Edward
  4. Phil
  5. Jen
  6. Sarah
  7. Edward
  8. Phil
  1. for name in favorite_languages.keys():
  2. print(f"Hi {name.title()}.")
  3. if name in friends:
  4. language = favorite_languages[name].title()
  5. print(f"\t{name.title()}, I see you love {language}!")
  1. Hi Jen.
  2. Hi Sarah.
  3. Sarah, I see you love C!
  4. Hi Edward.
  5. Hi Phil.
  6. Phil, I see you love Python!
  1. if 'erin' not in favorite_languages.keys():
  2. print('Erin, please take our poll!')
Erin, please take our poll!

6.3.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(f"{name.title()}, thank you for taking the poll!")

6.3.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. Ruby
  5. Python
  1. print('The following languages have been mentioned:')
  2. for language in set(favorite_languages.values()):
  3. print(language.title())
  1. The following languages have been mentioned:
  2. Python
  3. Ruby
  4. C

6.4 嵌套

6.4.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}
  1. aliens = []
  2. # 创建爱30个绿色的外星人
  3. for alien_number in range(30):
  4. new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
  5. aliens.append(new_alien)
  6. # 显示前5个外星人
  7. for alien in aliens[:5]:
  8. print(alien)
  9. print('...')
  10. print(f"Total number of aliens: {len(aliens)}")
  1. {'color': 'green', 'points': 5, 'speed': 'slow'}
  2. {'color': 'green', 'points': 5, 'speed': 'slow'}
  3. {'color': 'green', 'points': 5, 'speed': 'slow'}
  4. {'color': 'green', 'points': 5, 'speed': 'slow'}
  5. {'color': 'green', 'points': 5, 'speed': 'slow'}
  6. ...
  7. Total number of aliens: 30
  1. # 创建一个用于存储外星人的空列表
  2. aliens = []
  3. # 创建爱30个绿色的外星人
  4. for alien_number in range(30):
  5. new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
  6. aliens.append(new_alien)
  7. for alien in aliens[:3]:
  8. if alien['color'] == 'green':
  9. alien['color'] = 'yellow'
  10. alien['speed'] = 'medium'
  11. alien['points'] = 10
  12. # 显示前5个外星人
  13. for alien in aliens[:5]:
  14. print(alien)
  15. print('...')
  1. {'color': 'yellow', 'points': 10, 'speed': 'medium'}
  2. {'color': 'yellow', 'points': 10, 'speed': 'medium'}
  3. {'color': 'yellow', 'points': 10, 'speed': 'medium'}
  4. {'color': 'green', 'points': 5, 'speed': 'slow'}
  5. {'color': 'green', 'points': 5, 'speed': 'slow'}
  6. ...

6.4.2 在字典中存储列表

  1. # 存储所点比萨的信息
  2. pizza = {
  3. 'crust': 'thick',
  4. 'toppings': ['mushrooms', 'extra cheese'],
  5. }
  6. # 概述所点的比萨
  7. print(f"You ordered a {pizza['crust']}-crust pizza with the following toppings:")
  8. for topping in pizza['toppings']:
  9. print(topping)
  1. You ordered a thick-crust pizza with the following toppings:
  2. mushrooms
  3. extra cheese
  1. favorite_language = {
  2. 'jen': ['python', 'ruby'],
  3. 'sarah': ['c'],
  4. 'edward': ['ruby', 'go'],
  5. 'phil': ['python', 'haskell'],
  6. }
  7. for name, languages in favorite_language.items():
  8. print(f"\n{name.title()}'s favorite languages are:")
  9. for language in languages:
  10. print(f"\t{language.title()}")
  1. Jen's favorite languages are:
  2. Python
  3. Ruby
  4. Sarah's favorite languages are:
  5. C
  6. Edward's favorite languages are:
  7. Ruby
  8. Go
  9. Phil's favorite languages are:
  10. Python
  11. Haskell

6.4.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(f"\nUsername: {username}")
  15. full_name = f"{user_info['first']} {user_info['last']}"
  16. location = user_info['location']
  17. print(f"\tFull name: {full_name.title()}")
  18. print(f"\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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/1007566
推荐阅读
相关标签
  

闽ICP备14008679号