当前位置:   article > 正文

Python编程 从入门到实践 第六章 字典_python一本通第六章

python一本通第六章

1. 字典简介

  1. 字典是由一系列键值对组成,每个键都与一个值相关联,与键相关联的值可以是数字、字符串、列表、甚至是字典
  2. 字典名 = {键1:值1,键2:值2,依此类推}
  3. 最简单的字典只有一个键值对
alien_0 ={'color':'green'}
  • 1

2. 字典使用

要获取与键相关联的值,可依次指定字典名、放在方括号内的键名

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

2.1 访问字典中的值

>>> alien_0 ={'color':'green','points':5}
>>> new_points = alien_0['points']
>>> print("You just earned "+str(new_points)+" points!")
You just earned 5 points!
  • 1
  • 2
  • 3
  • 4

2.2 添加键—值对

  1. 字典是一种动态结构,可随时在其中添加键—值对
  2. 添加键值对,依次指定字典名、用方括号括起的键、相关联的值
  3. 注意:键—值对的排列顺序与添加顺序不同,Python不关心键—值对的添加顺序,只关心键—值对之间的关联关系**
>>> alien_0 ={'color':'green','points':5}
>>> print(alien_0)
{'color': 'green', 'points': 5}
>>> alien_0['x_position'] = 0
>>> alien_0['y_position'] = 25
>>> print(alien_0)
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2.3 删除键—值对

  1. 使用del 语句将相应的键—值对彻底删除
  2. 使用del 语句,必须指定字典名、要删除的键
>>> alien_0 ={'color':'green','points':5}
>>> print(alien_0)
{'color': 'green', 'points': 5}
>>> del alien_0['points']
>>> print(alien_0)
{'color': 'green'}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2.4 先创建一个空字典

使用字典来存储用户提供的数据或在编写能自动生成大量键—值对的代码时,通常需要先定义一个空字典

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

2.5 修改字典中的值

  1. 修改字典中的值,依次指定字典名、方括号括起的键、相关联的新值
alien_0 ={'color':'green'}
print("The alien is "+alien_0['color']+".")
alien_0['color'] = 'yellow'
print("The alien is now "+alien_0['color']+".")
  • 1
  • 2
  • 3
  • 4
The alien is green.
The alien is now yellow.
  • 1
  • 2
  1. 有趣例子
alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}
alien_0['speed'] = 'fast'
print("Original x-position: " + str(alien_0['x_position']))
if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
    x_increment = 3
alien_0['x_position']=alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
Original x-position: 0
New x-position: 3
  • 1
  • 2

2.6 由类似对象组成的字典

  1. 前面示例中,字典存储的是一个对象的多种信息;也可以使用字典来存储众多对象的同一种信息
  2. 定义好字典后,在最后一个键—值对的下一行添加一个右花括号,并缩进四个空格,使其与字典中的键对齐
  3. 可在最后一个键—值对后面也加上逗号,为以后在下一行添加键—值对做好准备
  4. print语句后续各行,用tab键将它们对齐并缩进一级,在最后一行末尾加上右括号
>>> favorite_languages = {
...     'jen':'python',
...     'sarah':'c',
...     'edward':'ruby',
...     'phil':'pyrhon',
...     }
>>> print("Sarah's favorite language is "+
...       favorite_languages['sarah'].title()+
...       ".")
Sarah's favorite language is C.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3. 遍历字典

3.1 遍历所有键—值对

  1. 列表名.items()
  2. 方法items()返回一个键—值对列表
  3. 遍历字典时,键—值对的返回顺序也与存储顺序不同;Python不关心键—值对的返回顺序,它只跟踪键和值之间的关联关系
>>> user_0 = {
...     'username':'efermi',
...     'first':'enrico',
...     'last':'fermi',
...     }
>>> for key ,value in user_0.items():
...     print("\nkey: "+key)
...     print("Value: "+value)
...

key: username
Value: efermi

key: first
Value: enrico

key: last
Value: fermi
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
>>> favorite_languages = {
...     'jen':'python',
...     'sarah':'c',
...     'edward':'ruby',
...     'phil':'pyrhon',
...     }
>>> for name,language in favorite_languages.items():
...     print(name.title() + "'s favorite language is "+
...           language.title() + ".")
...
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Pyrhon.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

3.2 遍历所有键

  1. 列表名.keys()
  2. 方法keys()返回一个包含字典中的所有键的列表
  3. 遍历字典时,会默认遍历所有的键,下面两种写法均可
for name in favorite_languages.keys():
for name in favorite_languages:
  • 1
  • 2
  1. 演示操作1:
>>> favorite_languages = {
...     'jen': 'python',
...     'sarah': 'c',
...     'edward': 'ruby',
...     'phil': 'pyrhon',
...     }
>>> for name in favorite_languages.keys():
...     print(name.title())
...
Jen
Sarah
Edward
Phil
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  1. 演示操作2:
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'pyrhon',
    }

friends = ['phil','sarah']

for name in favorite_languages.keys():
    print(name.title())

    if name in friends:
        print("    Hi " + name.title() +
              ", I see your favorite language is " +
              favorite_languages[name].title() + "!")

if 'erin' not in favorite_languages.keys():
    print("Erin,please take our poll!")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
Jen
Sarah
    Hi Sarah, I see your favorite language is C!
Edward
Phil
    Hi Phil, I see your favorite language is Pyrhon!
Erin,please take our poll!
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3.3 遍历所有值

  1. 遍历所有(未去重)
favorite_languages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
print("The following languages have been mentioned:")
for language in favorite_languages.values():
    print(language.title())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
The following languages have been mentioned:
Python
C
Ruby
Python
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 遍历所有,剔除重复值(使用集合set)
favorite_languages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
The following languages have been mentioned:
C
Python
Ruby
  • 1
  • 2
  • 3
  • 4

3.4 顺序遍历

3.4.1 顺序遍历键—值对

  1. 实际上还是以键来排序
>>> user_0 = {
...     'username':'efermi',
...     'first':'enrico',
...     'last':'fermi',
...     }
>>> for key ,value in sorted(user_0.items()):
...     print("\nkey: "+key)
...     print("Value: "+value)
...

key: first
Value: enrico

key: last
Value: fermi

key: username
Value: efermi
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

3.4.2 顺序遍历键

>>> favorite_languages = {
...     'jen': 'python',
...     'sarah': 'c',
...     'edward': 'ruby',
...     'phil': 'pyrhon',
...     }
>>> for name in sorted(favorite_languages.keys()):
...     print(name.title())
...
Edward
Jen
Phil
Sarah
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

3.4.3 顺序遍历值

  1. 顺序遍历值—未去重
favorite_languages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
print("The following languages have been mentioned:")
for language in sorted(favorite_languages.values()):
    print(language.title())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
The following languages have been mentioned:
C
Python
Python
Ruby
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 顺序遍历值—去重
favorite_languages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
print("The following languages have been mentioned:")
for language in sorted(set(favorite_languages.values())):
    print(language.title())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
The following languages have been mentioned:
C
Python
Ruby
  • 1
  • 2
  • 3
  • 4

4. 嵌套

4.1 列表中嵌套字典

  1. 演示操作
>>> alien_0 = {'color':'green','points':5}
>>> alien_1 = {'color':'yellow','points':10}
>>> alien_2 = {'color':'red','points':15}
>>> aliens = [alien_0,alien_1,alien_2]
>>> for alien in aliens:
...     print(alien)
...
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  1. 有趣的例子
aliens = []
for alien_number in range(30):
    new_alien = {'color':'green','points':5,'speed':'slow'}
    aliens.append(new_alien)
for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
    elif alien['color'] == 'yellow':
        alien['color'] = 'red'
        alien['speed'] = 'fast'
        alien['points'] = 15
for alien in aliens[0:5]:
    print(alien)
print("...")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4.2 字典中嵌套列表

  1. 每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表
  2. 演示操作1:
pizza = {
    'crust':'thick',
    'toppings':['mushrooms','extra cheese'],
    }
print("You ordered a " + pizza['crust'] + "-crust pizza" +
      " with the following toppings:")
for topping in pizza['toppings']:
    print("\t" + topping)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
You ordered a thick-crust pizza with the following toppings:
	mushrooms
	extra cheese
  • 1
  • 2
  • 3
  1. 演示操作2:
>>> favorite_languages = {
...     'jen': ['python','ruby'],
...     'sarah': ['c'],
...     'edward': ['ruby','go'],
...     'phil':['python','haskell'],
...     }
>>> for name ,languages in favorite_languages.items():
...     if len(languages) == 1:
...         for language in languages:
...             print("\n" + name.title() + " 's favorite language is: " + language.title())
...     elif len(languages) > 1:
...         print("\n" + name.title() + " 's favorite languages are:")
...         for language in languages:
...             print("\t" + language.title())
...

Jen 's favorite languages are:
        Python
        Ruby

Sarah 's favorite language is: C

Edward 's favorite languages are:
        Ruby
        Go

Phil 's favorite languages are:
        Python
        Haskell
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

4.3 字典中嵌套字典

>>> users = {
...     'aeinstein':{
...         'first':'albert',
...         'last':'einstein',
...         'location':'princeton'
...         },
...     'mcurie': {
...         'first': 'marie',
...         'last': 'curie',
...         'location': 'paris'
...         },
...     }
>>> for username,user_info in users.items():
...     print("\nUsername: " + username)
...     full_name = user_info['first'] + " " + user_info['last']
...     location = user_info['location']
...     print("\tFull name: " + full_name.title())
...     print("\tLocation: " + location.title())
...

Username: aeinstein
        Full name: Albert Einstein
        Location: Princeton

Username: mcurie
        Full name: Marie Curie
        Location: Paris
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

5. 章节跳转

  1. Python编程 从入门到实践 第一章 起步
  2. Python编程 从入门到实践 第二章 变量和简单数据类型
  3. Python编程 从入门到实践 第三章 列表简介
  4. Python编程 从入门到实践 第四章 列表操作
  5. Python编程 从入门到实践 第五章 if语句
  6. Python编程 从入门到实践 第六章 字典
  7. Python编程 从入门到实践 第七章 用户输入和while循环
  8. Python编程 从入门到实践 第八章 函数
  9. Python编程 从入门到实践 第九章 类
  10. Python编程 从入门到实践 第十章 文件和异常
  11. Python编程 从入门到实践 第十一章 测试代码
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/992839
推荐阅读
相关标签
  

闽ICP备14008679号