字典的示例:
list_0 = {"name": "apple", "count": 5}
- 添加键 — 值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
输出内容:
添加键 — 值对- 修改字典中的值
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
输出内容:
修改字典中的值- 删除键 — 值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
输出结果:
删除键 — 值对- 遍历所有的键 — 值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi'
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
- 遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title())
- 按顺序遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title())
- 遍历字典中的所有值,并合并相同的值
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for language in set(favorite_languages.values()):
print(language.title())
- 嵌套:字典列表
8.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)
8.2 示例二:
aliens = []
for alien_number in range(30):
alien_number = alien_number % 3
if alien_number == 0:
new_alien = {'color': 'green', 'points': 5}
elif alien_number == 1:
new_alien = {'color': 'yellow', 'points': 10}
elif alien_number == 2:
new_alien = {'color': 'red', 'points': 15}
aliens.append(new_alien)
for alien in aliens[0: 7]:
print(alien)
print("...")
- 嵌套:在字典中存储列表
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
per_favorite_language = "\n" + name.title() + "'s favorite languages are:"
for language in languages:
per_favorite_language += "\t" + language.title()
print(per_favorite_language)
- 嵌套:在字典中存储字典
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']
print("\tFull name: " + full_name.title())
location = user_info['location']
print("\tLocation: " + location.title())
本文参考自 《Python 编程:从入门到实践》
网友评论