Chapter 6 Dictionaries
6.1 A Simple Dictionary
花括号
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
6.2 Working with Dictionaries
key-value pairs
Each key is connected to a value.
6.2.1 Adding New 增加
alien_0['x_position'] = 0
6.2.2 Starting with an Empty Dictionary
alien_0 = {}
6.2.3 Modifying Values 调整值
alien_0 = {'color': 'green'} #初始
alien_0['color'] = 'yellow'
6.2.4 Removing 移除
alien_0 = {'color': 'green', 'points': 5}
del alien_0['points']
6.2.5 A Dictionary of Similar Objects
favorite_languages = { #然后换行,一个pair一行。注意缩进
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python', #在最后一个key-value pair后也加逗号,便于以后添加新pair
}
6.2.6 Using get() to Access Values
不确定该pair是否存在于字典中时
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)
#输出
No point value assigned.
get括号中的第二个声明:如果字典中没有该pair,返回的值。
6.3 Looping Through a Dictionary
6.3.1 Looping Through All Key-Value Pairs
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items(): #any name for the variables
print(f"\nKey: {key}")
print(f"Value: {value}")
6.3.2 Looping Through All the Keys in a Dictionary
for name in favorite_languages.keys():
for name in favorite_languages: #在loop a dictionary的时候,默认是loop keys
6.3.3 Looping Through a Dictionary’s Keys in a Particular Order
for name in sorted(favorite_languages.keys()):
6.3.4 Set 集合
集合(set)是一个无序的不重复元素序列。
可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
创建格式:
(){}[]区别
()tuple
{}set dictionary
[]list
6.3.5 Looping Through All Values in a Dictionary
for language in favorite_languages.values():
避免输出重复:使用set
for language in set(favorite_languages.values()):
6.4 Nesting 嵌套
A List of Dictionaries 字典列表
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)
更换字典中的key-value pairs:
# Make an empty list for storing aliens.
aliens = []
# Make 30 green 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
# Show the first 5 aliens.
for alien in aliens[:5]:
print(alien)
print("...")
A List in a Dictionary 在字典中存储列表
# Store information about a pizza being ordered.
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# Summarize the order.
print(f"You ordered a {pizza['crust']}-crust pizza "
"with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
A Dictionary in a Dictionary 在字典中存储字典
users = { #缩进使得代码更易读
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}