6. 字典
字典
一个简单的字典
alien = {'color': 'green', 'points': 5}
print(alien['color'])
print(alien['points'])
#输出
green
5
使用字典
键和值之间用冒号分割,键-值对之间用逗号分割。
访问字典中的值
获取与键相关联的值,可依次指定字典名和发放在方括号内的键:
print(alien['color'])
添加键-值对
字典是一种动态结构
alien = {'color': 'green', 'points': 5}
print(alien)
alien['x_position'] = 0
alien['y_position'] = 25
print(alien)
#输出
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
先创建一个空字典
alien = {}
alien['color'] = 'green'
alien['points'] = 5
修改字典中的值
删除键-值对
del alien['point']
由类似对象组成的字典
favorite_languages={
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
遍历字典
遍历所有的键-值对
声明两个变量,用于存储键-值对中的键和值。for循环第二部分包含字典名和方法items()
遍历字典时,键-值对的返回顺序也与存储
for name, language in favorite_languages.items():
print(name.title()+"'s favorite language is '" + language.title() + ".")
遍历字典中所有的键
keys() #可省略,输出不变
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())
遍历字典中所有的值
values() 没有考虑重复
favorite_languages={
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for language in favorite_languages.values():
print(language.title())
print('\n')
for language in set(favorite_languages.values()):
print(language.title())
将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套
字典列表
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)
在字典中存储列表
favorite_languages={
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite language are:")
for language in languages:
print("\t" + language.title())
users = {
'aeinstein': {
'first': 'albert',
'last': 'alinstein',
'location': 'princeton',
},
'mucrie': {
'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())