字典
dict{}:括起来的键值对是字典.{key:value}
字典中的key必须是可哈希的(不可变的).value没有限制.
整数.字符串.元组是不可变的,列表是可变的.
增:
例:
dic={"A":"a"}dic["B"]="b"print(dic) ==<{‘A‘: ‘a‘, ‘B‘: ‘b‘}>
例: 如果key重复了,value会被替换.
dic={"A":"a"}dic["B"]="b"dic["B"]="2" #赋值print(dic) ==<{‘A‘: ‘a‘, ‘B‘: ‘2‘}>
setdefault 如果字典中包含这个key则不再继续保存.
例:
dic={"A":"a"}dic.setdefault("C","c")print(dic) ==<"A":"a","C":"c">
dic.setdefault("C",3)print(dic) ==<"A":"a","C":"c">
删除:
(1)pop(key)
例:
dic={"A":"a","B":"b","C":"c"}dic.pop("A")print(dic) ==<{‘B‘: ‘b‘, ‘C‘: ‘c‘}>
例:
dic={"A":"a","B":"b","C":"c"}ret=dic.pop("A")print(ret) ==<a>
(2)del dic[key]
例:
dic={"A":"a","B":"b","C":"c"}del dic["B"]print(dic) ==<{‘A‘: ‘a‘, ‘C‘: ‘c‘}>
(3)popitem() 随机删除
例:
dic={"A":"a","B":"b","C":"c"}ret=dic.popitem()print(ret) ==<(‘C‘, ‘c‘)>print(dic) ==<{‘A‘: ‘a‘, ‘B‘: ‘b‘}>
(4)clear 清空
例:
dic={"A":"a","B":"b","C":"c"}dic.clear()print(dic) ==<{}>
修改:
(1)可以用key直接修改.
例:
dic1={"A":1,"D":"d","C":3}
dic1["C"]=dic1["C"]-2print(dic1) ==<{‘A‘: 1, ‘D‘: ‘d‘, ‘C‘: 1}>
(2)字典1.update(字典2) 把字典2添加的字典1中,如果字典2中key和字典1中的key重复则替换vlaue,如果不重复,则添加.
例:
dic={"A":"a","B":"b","C":"c"}dic1={"A":1,"D":"d","C":3}
dic.update(dic1)print(dic) ==<{‘A‘: 1, ‘B‘: ‘b‘, ‘C‘: 3, ‘D‘: ‘d‘}>
查找:
(1)用key直接查找
例:
dic={"及时雨":"宋江","小李广":"花荣","易大师":"剑圣"}
print(dic["易大师"]) ==<剑圣>
(2)get 如果key不存在则返回None,如果不想找回None可以添加一个默认值. key存在则返回value
例:
dic={"及时雨":"宋江","小李广":"花荣","易大师":"剑圣"}print(dic.get("李光","默认值")) ==<默认值>
(3)setdefault 先判断字典中有没有key,如果没有则添加. 再用这个key去字典中查询,返回查到的结果.
例:
dic={"及时雨":"宋江","小李广":"花荣"}ret=dic.setdefault("诺手","诺克")print(ret) ==<诺克> #查询print(dic) ==<{‘及时雨‘: ‘宋江‘, ‘小李广‘: ‘花荣‘, ‘诺手‘: ‘诺克‘}> #添加
相关操作:
(1)keys 返回所有的key 结果像集合像列表但不是列表 可以进行迭代循环.
例:
dic={"及时雨":"宋江","小李广":"花荣"}print(dic.keys()) ==<dict_keys([‘及时雨‘, ‘小李广‘])>
for s in dic.keys(): print(s) ==<及时雨 小李广>
(2)values 返回所有的value值 结果像集合像列表但不是列表 可以进行迭代循环.
例:
dic={"及时雨":"宋江","小李广":"花荣"}print(dic.values()) ==<dict_values([‘宋江‘, ‘花荣‘])>for s in dic.values(): print(s) ==<宋江 花荣>
(3)items 返回所有key,value值 结果像列表但不是列表,列表中的元素是元组.
例:
dic={"及时雨":"宋江","小李广":"花荣"}print(dic.items()) ==<dict_items([(‘及时雨‘, ‘宋江‘), (‘小李广‘, ‘花荣‘)])>#键值对for s in dic.items(): print(s) ==<(‘及时雨‘, ‘宋江‘) (‘小李广‘, ‘花荣‘)> print(s[0])==<及时雨 小李广> print(s[1])==<宋江 花荣>根据解构的一种算法:
dic={"及时雨":"宋江","小李广":"花荣"}for k,v in dic.items(): print(k) ==<及时雨 小李广> print(v)==<宋江 花荣>
解构,解包
例:
a,b=1,2print(a) ==<1>print(b) ==<2>
例:
a=1,2 ==> a=(1,2)print(a) ==<(1,2)>
例:
a,b=(1,2)print(a) ==<1>
字典的嵌套
例:
dic={"name":"汪峰", "age":58, "wife":{"name":"章子怡", "age":37, "salar":1800000}, "children":[{"name":"老大","age":18}, {"name":"老二","age":7}]}print(dic["wife"]["salar"]) ==<1800000>print(dic["children"][1]["age"]) ==<7> #第二个孩子的年龄
原文地址:https://www.cnblogs.com/gxj742/p/9275640.html
时间: 2024-10-08 17:37:19