字典体现了一种映射关系,字典的创建如下:
dict={key1:value1,key2:value,.......},左侧是字典名,右侧是字典的内容。key代表了映射的键,value代表了映射的值。
举个例子吧
container={'苹果':'A','香蕉':'B','橘子':'C'}
print(container)
print(container['苹果'])#打印桃子对应的值
当打印某一个映射键所对应的值时,使用print(container['苹果'])这样的形式。
空字典的创建以及赋值
创建:name={} ;或者name=dict()
赋值:name['key']=value
例如:
#price={}
price=dict()
price['apple']=5
price['banana']=4
print(price)
判断某一关键字是否在字典中
if '关键字' in 字典名:、
#price={}
price=dict()
price['apple']=5
price['banana']=4
if 'apple' in price:
print('apple的价格是%d'%(price['apple']))
else:
print('该水果不卖')
if 'watermelon' in price:
print('watermelon的价格是%d'%(price['watermelon']))
else:
print('该水果不卖')