一、字典
1、字典的定义及形式
{}表示,每次保存两个数据 key:value,键值对,例如 dic = {"大洋哥":“赵阳”}
value:任意的数据类型
key:必须是可哈希的(不可变的)
2、字典的特性
字典是无序的,字典中每项均为键值对、字典的操作没有切片。
3、字典的操作
字典的操作包括了增删改查。
1 dic = {"name":"bug_ming","age":12,"hobby":["抽烟","喝酒","烫头"],"phone":110} 2 print(dic) # 字典是无序的 3 print(dic["name"]) # 可以像索引一样获取字典中的值,但是通过字典的key来获取到的
3.1、增
1 dic = {"name":"bug_ming","age":12,"hobby":["抽烟","喝酒","烫头"],"phone":110} 2 dic["height"] = 180 # 如果key不存在,执行的是增加操作 3 print(dic) 4 dic["name"] = "wtf" # 如果key存在,执行的是修改操作 5 print(dic) 6 dic = {"name":"bug_ming","age":12,"hobby":["抽烟","喝酒","烫头"],"phone":110} 7 dic.setdefault("王小二") # 一个参数放的是key 8 dic.setdefault("王小二","弹溜溜") # 如果key不存在 新增 9 dic.setdefault("王小二","打篮球") # 如果key存在,不执行任何操作,有别于dic[]
3.2、删
1 dic = {"name":"bug_ming","age":12,"hobby":["抽烟","喝酒","烫头"],"phone":110} 2 # ret = dic.pop("name") # 返回的是括号内key对应的value 3 # print(ret) 4 # del dic["name"] # 可以删 缺点是没有返回值 5 # print(dic) 6 # dic.clear() # 清空整个字典 7 # print(dic) 8 # ret = dic.popitem() # 随机删,且返回由key和value组成的元组,可按照解构方法利用返回值 9 # print(ret) 10 # print(dic)
3.3、改
1 dic = {"name":"bug_ming","age":12,"hobby":["抽烟","喝酒","烫头"],"phone":110} 2 # dic["name"] = "allen" # 可以直接通过取出值来更改 3 # print(dic) 4 dic2 = {"name":"allen"} # 把dic2中的name更新到了dic中,改了dic中的name 5 dic.update(dic2) 6 print(dic) # dic 改变 7 print(dic2) # dic2 不改变
3.4、查
1 dic = {"name":"bug_ming","age":12,"hobby":["抽烟","喝酒","烫头"],"phone":110} 2 # print(dic["love"]) # KeyError: 'love' key不存在 3 # print(dic.get("love")) # dic.get("love") == dic["love"] key不存在返回None 4 # print(dic.get("love","查无此项")) # dic.get(key,default) 可用来查是否存在 5 # print(dic.keys()) # 取出字典中所有的key,得列表,可遍历 6 # for el in dic.keys(): 7 # print(el) 8 # print(dic.values()) # 取出字典中所有的value,得列表,可遍历 9 # for el in dic.values(): 10 # print(el) 11 # 从dic中获取到list列表. 列表中每一项都是一个元组(key,value) 通过解构可以直接把key和value获取到 12 print(dic.items()) 13 for k,v in dic.items(): 14 print(k) 15 print(v)
3.5、解构
1 # 解构 2 # a, b = (1, 5) 3 # print(a) 4 # print(b)
3.6、字典的嵌套
1 wangfeng = { 2 'name':'汪峰', 3 'age':46, 4 'wife':{ 5 'name':'章子怡', 6 'age':43 7 }, 8 'children':[ 9 {'name':'小叮当','age':10}, 10 {'name':'大叮当','age':16} 11 ] 12 } 13 # 汪峰的第二个儿子的年龄 14 print(wangfeng.get("children")[1].get("age")) 15 print(wangfeng.get("wife").get("name")) 16 print(wangfeng.get("name"))
1 dic = { 2 'name':['alex',2,3,5], 3 'job':'teacher', 4 'oldboy':{'alex':['python1','python2',100]} 5 } 6 # 1,将name对应的列表追加一个元素’wusir’。 7 dic['name'].append("wusir") 8 print(dic) 9 # 2,将name对应的列表中的alex首字母大写。 10 dic['name'][0] = dic['name'][0].capitalize() 11 print(dic) 12 # 3,oldboy对应的字典加一个键值对’老男孩’,’linux’。 13 dic['oldboy']['老男孩'] = 'linux' 14 print(dic) 15 # 4,将oldboy对应的字典中的alex对应的列表中的python2删除。 16 dic["oldboy"]['alex'].remove('python2') 17 print(dic)