目录
一、字典
在python中,字典是一系列键-值对,每个键与一个值关联。
car={
'color':'red','price':120,'User':'Tom'}
#car为字典名,'color'、'price'、'User'是键,'red'、120、'Tom'是对应的值
二、使用字典
1、访问字典中的值
要获取与键相关联的值,可依次指定字典名和放在方括号内的键。
car={
'color':'red','price':120,'User':'Tom'}
#car为字典名,'color'、'price'、'User'是键,'red'、120、'Tom'是对应的值
print(car['color'])
'''输出结果为:
red
'''
print("The car's price is: "+str(car['price'])+"万元")
#此处'price'关联的值为int需要转换
'''输出结果为:
The car's price is: 120万元
'''
2、添加键-值对
要添加键-值对,只需要依次指定字典名、用方括号括起的键和相关联的值。
car={
'color':'red','price':120,'User':'Tom'}
#car为字典名,'color'、'price'、'User'是键,'red'、120、'Tom'是对应的值
print(car)
'''输出结果为:
{'color': 'red', 'price': 120, 'User': 'Tom'}
'''
car['Birthday']='2021年XX月XX日'
print(car)
'''输出结果:
{'color': 'red', 'price': 120, 'User': 'Tom', 'Birthday': '2021年XX月XX日'}
'''