1、字典key-value,key是不能重复的stu_info={"name":"王志华","age":18,"addr":"北京"}2、取值,查print(stu_info[‘name‘])print(stu_info[‘age‘])print(stu_info[‘addr‘])# print(stu_info[‘we‘]) #取不存在的key的值,会报key不存在的错误#.get方法取值print(stu_info.get(‘name‘))print(stu_info.get(‘we‘)) #取不存在的key的值,会返回None,取值最好用.get方法,不会报错print(stu_info.get(‘login‘,500)) #如果值不存在,就返回逗号后面的值,这个返回500 2、修改stu_info[‘addr‘]=‘上海‘print(stu_info) 3、新增stu_info[‘phone‘]=123456stu_info.setdefault(‘email‘,‘[email protected]‘)print(stu_info)#新增一个不存在的key,不会修改value的值stu_info.setdefault(‘age‘,‘19‘)print(stu_info) 4、删除stu_info.pop(‘email‘)print(stu_info)del stu_info[‘age‘]print(stu_info) # stu_info.popitem() #从字典中随机删除一个元素# stu_info.clear() #清空字典stu_info[‘age‘]=20print(stu_info)5、把一个字典加到另外一个字典里d1={‘b‘:1}d2={‘a‘:2}d1.update(d2)#把d2加到d1中print(d1)6、循环字典print(stu_info.keys())#打印所有的keyprint(stu_info.values()) #打印所有的values#直接循环字典,打印出来都是字典中的keyfor i in stu_info: print(i)#判断key是否存在print(‘name‘in stu_info.keys())print(‘name‘ in stu_info) #第一种,这种效率比第二种效率高第一种,取key和value的值:for i in stu_info: s=‘%s=>%s‘%(i,stu_info.get(i)) print(s)#第二种for k,v in stu_info.items(): print(‘%s=>%s‘%(k,v)) print(stu_info.items()) 7、字典的嵌套
#字典嵌套stu_info={ ‘xiaoming‘:{"password":123456,"phone":1323214,"age":18,"addr":"北京"}, "xiaohei":{"password": 123456,"phone": 132321,"age": 18,"addr": "上海"}}print(stu_info[‘xiaoming‘][‘phone‘])d = { ‘春波‘:{ "car":{‘BMW‘:5,‘BENZ‘:3,‘audi‘:3,‘byd‘:4}, "house":["北京",‘南京‘,‘上海‘], "money":1000000,}, ‘乔美玲‘:{ "bag":[‘xx‘,‘lv‘,], "house":[‘三环‘,‘4环‘], "hzp":[‘skii‘,‘ysl‘], ‘language‘:{ ‘普通话‘:10, ‘东北话‘:20, ‘日语‘:0, ‘英语‘:4 } }} #1、马春波卖了一套上海的房子,买了500百万d[‘春波‘][‘house‘].pop(-1)print(d[‘春波‘][‘house‘]) d[‘春波‘][‘money‘]+=5000000print(d[‘春波‘][‘money‘])#2、算一下马春波有多少辆车car_num=d[‘春波‘][‘car‘].values()print(sum(car_num))#3、春波花了100百万买了一辆莱斯莱斯d[‘春波‘][‘money‘]-=1000000print(d[‘春波‘][‘money‘]) d[‘春波‘][‘car‘].setdefault(‘莱斯莱斯‘,1)print(d[‘春波‘][‘car‘])
#4、乔美玲的东北话从20级变成了10级d[‘乔美玲‘][‘language‘][‘东北话‘]-=10print(d[‘乔美玲‘][‘language‘][‘东北话‘])#5、乔美玲会哪几种语言for k in d[‘乔美玲‘][‘language‘]: print(k)
原文地址:https://www.cnblogs.com/qiuqiu64/p/10004525.html
时间: 2024-11-10 23:37:11