字典是一种key-value的数据类型,就像日常用的字典,通过字母或者笔画来查找对应页的详细内容。
字典是无序的,没有顺序。因为有key。
info = {'stu1001':'wang er','stu1002':'zhang san','stu1003':'li si' } print(info)#打印字典所有kv print(info['stu1001'])#打印key对应的value info['stu1001'] = '王二' info['stu1004'] = 'zhao liu'#有key就修改,没有key就添加 del info['stu1001']#删除某一kv info.pop('stu1002')#删除某一kv info.popitem()#随机删除一个kv print(info)info1 = {'stu1001':'wang er','stu1002':'zhang san','stu1003':'li si' } info1['stu1001']#查找某一个kv。确定有这个k才能用这种方法,否则会报错 print(info1.get('stu1004'))#安全的查找。如果没有这个值,会返回None print('stu1004' in info1)#查找字典里有没有这个元素,如果有返回True,没有返回false info.values()b = {'stu1001':'robin',1:3,2:5 } info1.update(b)#将两个字典合并,相同的key做更新 print(info1) c = info1.fromkeys([6,7,8],[1,{'name':'robin'},444])#初始化一个新的字典,如果只有一层没事。如果多层,会出现共享内存地址问题。一个改了,其他都改了。 print(c) c[7][1]['name'] = 'jack' print(c)print(info1.items())#把字典转成列表
多级字典嵌套及操作
字典可以多级嵌套,成为树状结构。
catalog = {'Europr':{'Germany':['beer','football','rigorous'],'Frence':['romantic','Napoleon','Paris'],'England':['Big Ben','London','Manchester'],'Italy':['Rome','Milan','Venice']},'Asia':{'China':['Beijing','Shanghai','Tianjing'],'Japan':['Tokyo','Osaka','Nagoya'],'Korea':['Seoul','Jeju']},'North America':{'USA':['Washington','New York','Los Angel'],'Canada':['Toronto','Montreal']} } catalog['Asia']['China'][1]='Chongqing'print(catalog.values())#打印所有的value print(catalog.keys())#打印所有的key catalog.setdefault('Africa',{'South Africa':[1,2,3],'Libya':[5,6,7],'Zimbabwe':[8,9,0]})#如果有这个值,返回;没有这个值,创建新的# print(catalog)
字典的循环
info2 = {'stu1001':'wang er','stu1002':'zhang san','stu1003':'li si' } print(info2) for i in info2:print(i,info2[i]) #最常用的循环方式,比下面的高效for k,v in info2.items(): #先把字典转成列表,费时间print(k,v)