在Python中,字典用放在花括号{}中的是一系列键-值对表示。每个键都与一个值相关联,可以使用键来方炜相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。
alien_0 = {'color': 'green','point': 5}
print(alien_0['color'])
print(alien_0['point'])
#green
#5
添加键-值对
alien_0 = {'color': 'green','point': 5}
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#{'color': 'green', 'point': 5, 'x_position': 0, 'y_position': 25}
创建空字典
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
#{'color': 'green', 'points': 5}
修改字典中的值
alien_0 = {'color':'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print(alien_0)
#The alien is green.
#{'color': 'yellow'}
删除键-值对 del
alien_0 = {'color': 'green','points': 5}
print(alien_0)
del alien_0['color']
print(alien_0)
#{'color': 'green', 'points': 5}
#{'points': 5}
由类似对象组成的字典
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python'
}
print("Sarah's favorite language is " + favorite_languages['sarah'].title() + '.')
#Sarah's favorite language is C.
遍历所有的键-值对,使用方法item()
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key,value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
#Key: username
#Value: efermi
#Key: first
#Value: enrico
#Key: last
#Value: fermi
遍历字典中的所有键,使用方法keys()
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title())
#Jen
#Sarah
#Edward
#Phil
按顺序遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
#Edward, thank you for taking the poll.
#Jen, thank you for taking the poll.
#Phil, thank you for taking the poll.
#Sarah, thank you for taking the poll.
遍历字典中的所有值
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned: ")
for language in favorite_languages.values():
print(language.title())
#Python
#C
#Ruby
#Python
字典列表
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)
#{'color': 'green', 'points': 5}
#{'color': 'yellow', 'points': 10}
#{'color': 'red', 'points': 15}
aliens = []
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("...")
print("Total number of aliens: " + str(len(aliens)))
在字典中存储列表
pizza = {
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}
print("You ordered a " + pizza['crust'] + "-crust pizza " + "with the following toppings: ")
for topping in pizza['toppings']:
print("\t" + topping)
#You ordered a thick-crust pizza with the following toppings:
# mushrooms
# extra cheese
在字典中存储字典
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())
#Username: aeinstein
# Full name: Albert Einstein
# Location: Princeton
#
#Username: mcurie
# Full name: Marie Curie
# Location: Paris