第6章:字典
字典示例(查)
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
字典的增、改、删
# 创建一个空字典
alien_0 = {}
# 增加键值对
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
# 修改颜色
alien_0['color'] = 'yellow'
print(alien_0)
# 删除键值对
del alien_0['color']
print(alien_0)
输出:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 5}
{'points': 5}
遍历键值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey:" + key)
print("Value:" + value)
favorite_languages = {
'sarah': 'C',
'jack': 'Python',
'sam': 'Javascript',
'bruce': 'Rust',
}
for name, language in favorite_langueages.items():
print(name.title() + "'s favorite language is " + language + ".")
注意: 即便遍历字典时,键—值对的返回顺序也与存储顺序不同。Python不关心键—值对的存储顺序,而只跟踪键和值之间的关联关系。
遍历字典中的所有键
不需要使用字典中的值时,方法keys() 很有用
favorite_languages = {
'sarah': 'C',
'jack': 'Python',
'sam': 'Javascript',
'bruce': 'Rust',
}
for name in favorite_languages.keys():
print(name.title())
另一种遍历键值对的方式
favorite_languages = {
'sarah': 'C',
'jack': 'Python',
'sam': 'Javascript',
'bruce': 'Rust',
}
for name in favorite_languages:
print(name.title() + "'s favorite language is " + favorite_langueages[name] + ".")
注意: 遍历字典时,会默认遍历所有的键,因此,如果将上述代码中的for name in favorite_languages.keys(): 替换为for name in favorite_languages: ,输出将不变。
利用函数sorted() 按顺序遍历所有的键
favorite_languages = {
'sarah': 'C',
'jack': 'Python',
'sam': 'Javascript',
'bruce': 'Rust',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll."
遍历字典中的所有值
如果你感兴趣的主要是字典包含的值,可使用方法values() ,它返回一个值列表,而不包含任何键。
favorite_languages = {
'sarah': 'C',
'jack': 'Python',
'sam': 'Javascript',
'bruce': 'Rust',
'tim': 'Python'
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language)
输出:
The following languages have been mentioned:
C
Python
Javascript
Rust
Python
这种做法提取字典中所有的值,而没有考虑是否重复。涉及的值很少时,这也许不是问题,但如果被调查者很多,最终的列表可能包含大量的重复项。为剔除重复项,可使用集合(set)。集合 类似于列表,但每个元素都必须是独一无二的
favorite_languages = {
'sarah': 'C',
'jack': 'Python',
'sam': 'Javascript',
'bruce': 'Rust',
'tim': 'Python'
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language)
输出:
The following languages have been mentioned:
Python
Rust
C
Javascript
查资料后,对集合的补充:python3-集合|菜鸟教程
嵌套
列表中存储字典
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 = {
'bruce': ['java'],
'tom': ['python', 'c'],
'david': ['php', 'rust', 'go'],
'jack': ['java'],
}
for name, languages in favorite_languages.items():
print("\n" + name + "'s favorite languages are:" )
for language in languages:
print(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']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())
习题
6-1
user = {
'firstname': 'burce',
'lastname': 'zhang',
'city': 'beijing',
'age': 18,
}
print("firstname: " + user['firstname'].title())
print("lastname: " + user['lastname'].title())
print("city: " + user['city'].title())
print("age: " + str(user['age']))
6-2
favorite_numbers = {
'bruce': 5,
'tom': 8,
'jerry': 6,
}
for name, number in favorite_numbers.items():
print(name + "'s favorite number is " + str(number) + ".")
6-3
program_vocabulary = {
'print': '输出到屏幕上',
'variable': '变量',
'set': '集合',
'list': '列表',
'dict': '字典',
}
for vocabulary, meaning in program_vocabulary.items():
print("\n" + vocabulary + ":\n\t" + meaning)
6-5
rivers = {
'nile': 'egypt',
'amazon river': 'brazil',
'yangzi river': 'china',
}
for name, country in rivers.items():
print("The " + name.title() + " runs through " + country.title() + ".")
6-6
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
persons = ['jim', 'sam', 'ben', 'phil', 'sarah']
for person in persons:
if person in favorite_languages.keys():
print(person.title() + ",thank you for taking the poll!")
else:
print(person.title() + ",please take the poll,thank you.")
6-7
user_0 = {
'firstname': 'burce',
'lastname': 'zhang',
'city': 'beijing',
'age': 18,
}
user_1 = {
'firstname': 'jack',
'lastname': 'ma',
'city': 'hangzhou',
'age': 58,
}
user_2 = {
'firstname': 'robin',
'lastname': 'li',
'city': 'beijing',
'age': 40,
}
users = [user_0, user_1, user_2]
for user in users:
print(user)
6-8
cat = {
'owner' : 'bruce',
'type': 'persian',
}
dog = {
'owner': 'sam',
'type': 'korgi',
}
pets = [cat, dog]
for pet in pets:
print("This is a " + pet['type'].title() +", its owner is " + pet['owner'] .title()+ ".")
6-9
favorite_places = {
'tom': ['beijing', 'chengdu', 'shanghai'],
'jim': ['wuhan', 'chongqing', 'beijing'],
'bruce': ['wuhan']
}
for name, places in favorite_places.items():
if len(places) == 1:
print("\n" + name + "'s favorite place is " + places[0] + ".")
else:
print("\n" + name + "'s favorite places are:")
for place in places:
print(place)
6-10
# 与6-9类似
6-11
cities = {
'wuhan': {
'country': 'China',
'population': 11212000,
'fact': 'Wuhan,different everyday!'
},
'beijing': {
'country': 'China',
'population': 21536000,
'fact': 'Some people leave,and some people come in the meantime.'
}
}
for city, city_info in cities.items():
print("\ncity:" + city)
print("country:" + city_info['country'])
print("population:" + str(city_info['population']))
print("fact" + city_info['fact'])