1. 程式人生 > >18.07.06

18.07.06

val 汪峰 set 包含 不可 value 解構 {} ret

字典

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"]-2
print(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,2
print(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> #第二個孩子的年齡

18.07.06