Python编程:从入门到实践 (五)

第六章 字典

#下面是一个简单的字典,存储了有关特定外星人的信息:
#在Python中,字典是一系列键-值对。
#每个键都与一个值相关联,可以使用键来访问与之相关联的值
#可将任何Python对象用作字典中的值
#在Python中,字典用放在花括号{}中的一系列键-值对表示
#键-值对是两个相关联的值。指定键时,Python将返回与之相关联的值
#键和值之间用冒号分隔,而键-值对之间用逗号分隔
alien_0 = {'color': 'green', 'points': 5}
#要获取与键相关联的值,可依次指定字典名和放在方括号里的键
print(alien_0['color'])
print(alien_0['points'])
new_points = alien_0['points']
print("you just earned " + str(new_points) + " points!")

#添加键-值对
#字典是一种动态结构,可随时在其中添加键-值对
#要添加键-值对,可依次指定字典名、用方括号括起来的键和相关联的值
#键-值对的排列顺序与添加顺序不同,Python不关心键-值对的添加顺序,而只关心键与值之间的关联关系
alien_0['x_position'] = 0
alien_0['y_position'] = 25

print(alien_0)

#有时候在空字典中添加键-值对是为了方便,而有时候必须这样做
#使用字典来存储用户提供的数据或者在编写能自动生成大量键-值对的代码时,通常都需要先定义一个空字典

#修改字典中的值
#要修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值
print("The alien is " + alien_0['color'])
alien_0['color'] = 'yellow'
print("The alien is " + alien_0['color'])
#对一个能够以不同速度移动的外星人的位置进行跟踪
alien_0['speed'] = 'medium'
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']))

#删除键-值对
#对于字典中不再需要的信息,可使用del语句将相应的键-值对彻底删除
#使用del语句时,必须指定字典名和要删除的键
#删除的键-值对就永远消失了
print(alien_0)
del alien_0['points']
print(alien_0)

#由类似对象组成的字典
favorite_language = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
print("Sarah's favorite language is " +
            favorite_language['sarah'].title() + '.')

输出:

green
5
you just earned 5 points!
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
The alien is green
The alien is yellow
Original x-position: 0
New x-position: 2
{'color': 'yellow', 'points': 5, 'x_position': 2, 'y_position': 25, 'speed': 'medium'}
{'color': 'yellow', 'x_position': 2, 'y_position': 25, 'speed': 'medium'}
Sarah's favorite language is C.

6-3 遍历字典

#鉴于字典可能包含大量的数据,Python支持对字典遍历。
#字典可用于以各种方式存储信息,因此有多种遍历字典的方式:可遍历字典的所有键-值对、键或值
user_0 = {
    'user_name': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
}
#使用一个for循环来遍历这个字典
#注意,即使遍历字典时,键-值对的返回顺序也与存储顺序不同
#Python不关心键-值对的存储顺序,而只追踪键和值之间的关联关系
for key, value in user_0.items():
    print("\nKey: " + key)
    print("Value: " + value)
 
#遍历字典中的所有键-值对
favorite_language = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}

#遍历字典中的所有键
#在循环中,可使用当前键来访问与之相关联的值。
for name in favorite_language.keys():
    print(name.title())
friends = ['phil', 'sarah']
for name in favorite_language.keys():
    print(name.title())
    if name in friends:
        print("Hi " + name.title() + 
                ", I see you favorite language is " + 
                favorite_language[name].title() + "!") 
#还可以使用keys()确定某个人是否接受了调查
#方法keys()并非只能用来遍历,实际上,他返回一个列表,其中包含字典中的所有键
if 'erin' not in favorite_language.keys():
    print("Erin, please take our poll!")

#按顺序遍历字典中的所有键
#要以特定的顺序返回元素,一种方法是在for循环中对返回的键进行排序。
#为此,可使用函数sorted()来获得按照特定顺序排列的键列表的副本
for name in sorted(favorite_language.keys()):
    print(name.title() + ", thank you for taking the poll.")

#遍历字典中的所有值
#如果你感兴趣的主要是字典包含的值,可使用方法values()
#它返回一个值列表,而不包含任何键
print("The following language have been mentioned: ")
for language in favorite_language.values():
    print(language.title())
#这种做法提取字典中所有的值,而没有考虑是否重复。
#为剔除重复项,可使用集合(set)
#集合类似于列表,但每个元素都必须是独一无二的
#通过对包含重复元素的列表调用set(),可使用Python找出列表中独一无二的元素,并使用这些元素来创建一个集合
for language in set(favorite_language.values()):
    print(language.title())


输出:


Key: user_name
Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi
Jen
Sarah
Edward
Phil
Jen
Sarah
Hi Sarah, I see you favorite language is C!
Edward
Phil
Hi Phil, I see you favorite language is Python!
Erin, please take our poll!
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
The following language have been mentioned:
Python
C
Ruby
Python
C
Ruby
Python

6-4 嵌套

#将一系列字典存储在列表中,或者将列表作为值存储在字典中
#这称为嵌套
alien_0 = {'color': 'green', 'point': 5}
alien_1 = {'color': 'yellow', 'point': 10}
alien_2 = {'color': 'red', 'point':15}

aliens = [alien_0, alien_1,  alien_2]

for alien in aliens:
    print(alien)
#更符合现实的情形是,外星人不止三个,且每个外星人都是使用代码自动生成的
#在下面的示例中,使用range()生成了30个外星人
#首先创建一个用于存储外星人的空列表
aliens = []
#创建30个绿色的外星人
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)
#显示前五个外星人
for alien in aliens[:5]:
    print(alien)
print("...")
#显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))
#将前三个外星人修改成黄色的、速度为中等且值10个点
for alien in aliens[0:3]:
    # print(alien)
    # alien['color'] = 'zfb is my husband'
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
    
for alien in aliens[0:5]:
    print(alien)
print("...") 

输出:

{'color': 'green', 'point': 5}
{'color': 'yellow', 'point': 10}
{'color': 'red', 'point': 15}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30
{'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'}
...
#在字典中存储列表
#每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表
pizza = {
    'crust': 'thick',
    'toppings': ['myshrooms', 'extracheese'],
}
print("You ordered a " + pizza['crust'] + "-crust pizza "+
        "with the following toppings:")

for topping in pizza['toppings']:
    print("\t" + topping)

输出:

You ordered a thick-crust pizza with the following toppings:
        myshrooms  
        extracheese
#在字典中存储字典
users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'priceton',
    },
    '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: Priceton

Username: mcurie
        Full name: Marie Curie
        Location: Paris
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值