第六章 字典

6.1 一个简单的字典

alien_0 = {‘color' : 'green', 'points' : 5}

6.2 使用字典

在 python 中,字典是一系列键值对,放在花括号中({ }),可以用键来访问与其相关联的值

6.2.1 访问字典中的值

根据键访问其关联的值

alien_0 = {'color': 'green', 'points': 5}
print(f"You earned {alien_0['points']} points.") # 用alien_0['points']访问
'''
输出:
You earned 5 points.

'''

6.2.2 添加键值对

添加 x, y 坐标

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)

alien_0['x_position'] = 0  #新增 {'x_position': 0} 键值对
alien_0['y_position'] = 25  #新增 {'y_position': 25} 键值对
print(alien_0)
'''
输出:
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

'''

6.2.3 先创建一个空字典

alien_0 = {}

6.2.4 修改字典中的值

要修改字典的值,可直接用键值进行索引,并重新赋值

alien_0 = {'color': 'green', 'points': 5}
print(f"The alien is {alien_0['color']}.")

alien_0['color'] = 'yellow'
print(f"Now the alien is {alien_0['color']}.")
'''
输出:
The alien is green.
Now the alien is yellow.

'''

6.2.5 删除键值对

使用 del 语句

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)

del alien_0['color']
print(alien_0)
'''
输出:
{'color': 'green', 'points': 5}
{'points': 5}
'''

6.2.6 由类似对象组成的字典

6.2.7 使用 get() 来访问值

方法 get( x[, ]) 可以避免在查找一个不存在的键值时弹出错误
它有两个参数,第一个参数是必须的,表示查找的键值,第二个参数是可选的,指出查找不到时的返回值,默认为空

alien_0 = {'color': 'green', 'points': 5}

speed_value = alien_0.get('speed', "No speed value assigned.")
print(speed_value)
'''
输出:
No speed value assigned.

'''

6.3 遍历字典

6.3.1 遍历所有键值对

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}
for name, language in favorite_languages.items(): #方法items()返回一个键值对列表
    print(f"{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 Python.
'''

6.3.2 遍历字典中的所有键值

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}
for name in favorite_languages.keys():  #方法keys()返回一个键列表
    print(name.title())

'''
输出:
Jen
Sarah
Edward
Phil

'''

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

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}
for name in sorted(favorite_languages.keys()):
    print(name.title())
print(sorted(favorite_languages.keys()))
'''
输出:
Edward
Jen
Phil
Sarah
['edward', 'jen', 'phil', 'sarah']

'''

6.3.4 遍历字典中的所有值

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}

print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):  # set()是一个集合函数
    print(language.title())
print(set(favorite_languages.values()))
'''
输出:
The following languages have been mentioned:
Python
Ruby
C
{'python', 'ruby', 'c'}           (这个输出就是一个集合)

'''

集合用 { } 表示,集合中不能存在重复的元素

6.4嵌套

嵌套:一系列字典存储在列表中,或者列表作为值存储在字典中,这种方式称为嵌套

6.4.1 字典列表

字典列表是一个列表,列表中的元素是字典

# 创建一个空列表存储外星人
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(f"\nTotal number of aliens: {len(aliens)}.")
'''
输出:
{'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.
'''

6.4.2 在字典中存储列表

favorite_languages = {
    'jen': ['python', 'ruby'],
    'sarah': ['c'],
    'edward': ['ruby', 'go'],
    'phil': ['python', 'haskell']
}
for name, languages in favorite_languages.items():
    print(f"\n{name.title()}'s favorite languages are:")
    for language in languages:
        print(f"\t{language.title()}")
'''
输出:

Jen's favorite languages are:
	Python
	Ruby

Sarah's favorite languages are:
	C

Edward's favorite languages are:
	Ruby
	Go

Phil's favorite languages are:
	Python
	Haskell

'''

6.4.3 在字典中存储字典

users = {
    'aeinstein':{
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton'
    },
    'mcurie':{
        'first': 'marie',
        'last': 'curie',
        'location':'paris'
    }
}

for user_name, user_info in users.items():
    print(f"\nUsername: {user_name}")

    full_name = f"{user_info['first']} {user_info['last']}"
    location = user_info['location']

    print(f"\tFull name:{full_name.title()}")
    print(f"\tLocation:{locatio
'''
输出:

Username: aeinstein
	Full name:Albert Einstein
	Location:Princeton

Username: mcurie
	Full name:Marie Curie
	Location:Paris

'''

6.5 小结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张小勇zhangxy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值