1. 一个简单的字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
2. 使用字典
- 在Python中,字典 是一系列 键值对。每个键都与一个值相关联,你可以用键来访问相关联的值
- 与键相关联的值可以是任何Python对象,例如数、字符串、 列表或者字典
- 字典表示格式:
dictionary_name = {'attr1': 'value1', 'attr2': 'value2' ...}
- 要获取与键相关联的值,格式为:
dictionary_name['attr1']
添加键值对
- 字典是一种动态结构,可随时在其中添加键值对
- 添加键值对格式:
dictionary_name['attr3'] = value3
先创建一个空字典
- 使用字典来存储用户提供的数据或在编写能自动生成大量键值对的代码时,通常需要先定义一个空字典
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
修改字典中的值
- 修改格式与添加键值对的格式相同:
dictionary_name['attr1'] = value1
删除键值对
del dictionary_name['attr2'] = value2
由类似对象组成的字典
- 字典存储的可以是一个对象的多种信息,也可以是众多对象的同种信息
favorite_language = {
'jen': 'python',
'sarah': 'C',
'edward': 'ruby',
'phil': 'python',
}
使用get()来访问值
- 使用
dictionary_name['attr1']格式访问指定键时,若键不存在,则会导致Python显示traceback,指出存在键值错误(KeyError)
- 可使用
方法get()在指定的键不存在时返回指定的默认值,避免报错
方法get()格式:
dictionary_name.get('attr1', 'return value if not exist')
3. 遍历字典
方法items()返回包含字典中所有键值对的列表 格式: dictionary_name.items()
方法keys()返回包含字典中所有键的列表 格式: dictionary_name.keys()
方法values()返回包含字典中所有值的列表 格式: dictionary_name.values()
favorite_language = {
'jen': 'python',
'sarah': 'C',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_language.items():
print(f"{name.title()}'s favorite language is {language.title()}.")
for name in sorted(favorite_language.keys()):
print(f"{name.title()}, thank you for taking the poll.")
for language in set(favorite_language.values()):
print(f"{language.title()} has been mentioned.")
4. 嵌套
字典列表
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[:5]:
print(alien)
print("...")
print(f"Total number of aliens: {len(aliens)}")

在字典中存储列表
favorite_language = {
'jen': ['python', 'ruby'],
'sarah': 'C',
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_language.items():
if len(languages) == 1:
print(f"{name.title()}'s favorite language is {languages.title()}.")
else:
print(f"{name.title()}'s favorite language are: ")
for language in languages:
print(f"\t{language.title()}")

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

文章中的所有代码经测试均可成功编译运行,可直接复制。具有显然结果或简单结论的代码不展示运行结果。如有问题欢迎随时交流~