alien_0={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
2、使用字典
(1)访问字典
方括号表示法
new_points=alien_0['points']
print(f"You just earned {new_points} points!")#You just earned 5 points!
get():若指定的键可能不存在,应考虑使用get()
speed_value=alien_0.get('speed','No speed value assigned.')
print(speed_value) #No speed value assigned.
(2)添加与删除键值对
添加
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)#{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
删除
del alien_0['points']
print(alien_0)#{'color': 'yellow', 'x_position': 0, 'y_position': 25}
alien_0.clear()#清除
print(alien_0)#{}
(3)修改字典中的值
alien_0['color']='yellow'#修改
print(f"The alien is now {alien_0['color']}")#The alien is now yellow
(4)由类似对象组成的字典
favorite_language={
'jen':'python',
'sarah':'C',
'edward':'Java',
'phil':'python,'
}
language=favorite_language['sarah'].title()
print(f"Sarah's favorite language is {language}")#Sarah's favorite language is C
3、遍历字典
user_0={
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
(1)遍历键值对
for key,value in user_0.items():#
print(f"nKey:{key}")
print(f"Value:{value}")
#Key:username
#Value:efermi
#Key:first
#Value:enrico
#Key:last
#Value:fermi
(2)遍历所有键
for key in user_0.keys():#遍历所有键
print(f"Key:{key}")
#Key:username
#Key:first
#Key:last
(3)按序遍历所有键
for key in sorted(user_0.keys()):#按序遍历所有键
print(f"Key:{key}")
#Key:first
#Key:last
#Key:username
(4)遍历所有值
for value in user_0.values():#遍历所有值
print(f"Value:{value}")
#Value:efermi
#Value:enrico
#Value:fermi
4、嵌套
(1)字典列表
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)
(2)在字典中存储列表
pizza={
'crust':'thick',
'toppings':['musroooms','extra cheese'],
}
print(f"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:
#musroooms
#extra cheese
(3)在字典中存储字典
users={
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton'
},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris'
},
}
for username,users_info in users.items():
print(f"nUsername:{username}")
full_name=f"{users_info['first']} {'last'}"
location=users_info['location']
print(f"tFull name:{full_name.title()}")
print(f"tLocation:{location.title()}")
#Username:aeinstein
# Full name:Albert Last
# Location:Princeton
#Username:mcurie
# Full name:Marie Last
# Location:Paris
(4)用用户输入来填充字典
responses={}
polling_active=True #设置一个标志指出调查是否继续
while polling_active: #提示输入被调查者的名字和回答
name=input("nWhat is your name?")
response=input("Which mountain would you like to climb someday?")
responses[name]=response#将回答存在字典中
repeat=input("Would you like to let another person respond?(Yes/No)")#看是否还有人参与调查
if repeat=='No':
polling_active=False
#调查结束显示结果
print("n---Poll Result---")
for name,response in responses.items():
print(f"{name} would like to climb {response}")
#What is your name?L
#Which mountain would you like to climb someday?Mountain Tai
#Would you like to let another person respond?(Yes/No)Yes
#What is your name?J
#Which mountain would you like to climb someday?Mountain Hua
#Would you like to let another person respond?(Yes/No)No
#---Poll Result---
#L would like to climb Mountain Tai
#J would like to climb Mountain Hua


