#字典是k-v形式,无序。key唯一
students={‘0001‘:‘张三‘,‘0002‘:‘李四‘,‘0003‘:‘王五‘}
#字典方法
print(students.items()) #打印字典里k-v
print(students.keys()) #打印字典的key值
print(students.values()) #打印字典的value值
add={‘0001‘:‘hi‘,‘a‘:‘b‘,4:5} #update方法更新字典
students.update(add)
print(students)
#查找
print(‘0001‘in students) #通过key判断
print(students.get(‘0001‘)) #通过get获取
print(students.get(‘0011‘)) #key不存在,返回None
print(students[‘0001‘]) #直接通过key获取v
print(students[‘0011‘]) #key不存在,会报错
#增加
students[‘0004‘]=‘new‘
print(students)
students.setdefault(‘0005‘,‘default‘) #用setdefault方法增加
print(students)
#修改
students[‘0004‘]=‘change‘ #指定key修改
print(students)
#删除
students.pop(‘0004‘) #删除法1
print(students)
del students[‘0004‘] #删除法2
print(students)
students.popitem() #随机删除
print(students)
students.clear() #清空字典
print(students)
#多级嵌套字典
people = {
‘田雨‘:{
‘age‘:18,
‘money‘:200000,
‘clothes‘:‘100套‘,
‘hzp‘:‘n多‘,
‘shoes‘:[‘nike‘,‘addis‘,‘lv‘,‘chanle‘]
},
‘张流量‘:{
‘金库‘:‘2000w‘,
‘house‘:[‘三环一套‘,‘4环2套‘],
‘cars‘: {
‘japan‘:[‘普拉多‘,‘兰德酷路泽‘],
‘usa‘:[‘林肯‘,‘凯迪拉克‘,‘福特‘],
‘china‘:[‘五菱宏光‘,‘qq‘,‘红旗‘]
}
}
}
print(people[‘张流量‘][‘cars‘][‘china‘][1]) #嵌套字典查询
people[‘张流量‘][‘cars‘][‘china‘].append(‘吉利‘) #字典嵌套列表追加
print(people)
for i in people: #循环打印key
print(i)
for k,v in people.items():
print(k,v)