1. 程式人生 > >python字典操作

python字典操作

python字典 python基礎

1、定義字典

>>> d1 = { //key-value的格式

"student1":"xiaoming",

"student2":"zhangsan",

"student3":"lisi"

}

2、查看

>>> print(d1["student1"]) //在已知有此key的情況下使用,在沒有此key時會報錯

xiaoming

>>> print(d1.get("student2")) //get方法不會報錯

zhangsan

>>> print(d1.get("student1"))

None


3、修改key的值

>>> print(d1["student1"])

xiaoming

>>> d1["student1"] = "XiaoMing" //如果存在則修改,不存在則添加

>>> print(d1["student1"])

XiaoMing


4、刪除

>>> del d1["student1"]

>>> print(d1)

{'student2': 'zhangsan', 'student3': 'lisi'}


5、判斷字典裏有沒有某數據

>>> print("student1" in d1)

False


6、多級字典的嵌套

>>> d2 = {

"weibo":{

"guomao":["wilson","david","lucia"],

"bagou":["zhangsan","wangwu","lisi"]},

"xindongfang":{

"yuquan":["piter","alen","cc"],

"wukesong":["shenyang","lidong","wangwei"]}

}


7、修改嵌套菜單中的值

>>> print(d2["weibo"]["guomao"])

['wilson', 'david', 'lucia'] //修改之前

>>> d2["weibo"]["guomao"][1] = "大衛"

>>> print(d2["weibo"]["guomao"])

['wilson', '大衛', 'lucia'] //修改之後


8、打印字典中的所有值

>>> print(d2.values())


9、打印字典中所有的key

>>> print(d2.keys())


10、如果字典中存在此鍵則返回,不存在則創建

>>> print(d2)

{'weibo': {'guomao': ['wilson', '大衛', 'lucia'], 'bagou': ['zhangsan', 'wangwu', 'lisi']}, 'xindongfang': {'yuquan': ['piter', 'alen', 'cc'], 'wukesong': ['shenyang', 'lidong', 'wangwei']}}

>>> d2.setdefault("weibo",{"xinhua":["aa","bb","cc"]})

{'guomao': ['wilson', '大衛', 'lucia'], 'bagou': ['zhangsan', 'wangwu', 'lisi']}

>>> d2.setdefault("yingfu",{"xinhua":["aa","bb","cc"]})

{'xinhua': ['aa', 'bb', 'cc']}

>>> print(d2)

{'weibo': {'guomao': ['wilson', '大衛', 'lucia'], 'bagou': ['zhangsan', 'wangwu', 'lisi']}, 'xindongfang': {'yuquan': ['piter', 'alen', 'cc'], 'wukesong': ['shenyang', 'lidong', 'wangwei']}, 'yingfu': {'xinhua': ['aa', 'bb', 'cc']}}


11、合並兩個字典,如果字典中有相同的key則更新,沒有則添加

>>> d1

{'student2': 'zhangsan', 'student3': 'lisi'}

>>> d3 = {"student2":"AAAA","BBBBB":"CCCCC",1:2}

>>> d1.update(d3)

>>> print(d1)

{'student2': 'AAAA', 'student3': 'lisi', 'BBBBB': 'CCCCC', 1: 2}


12、把字典轉換成列表

>>> print(d1.items())

dict_items([('student2', 'AAAA'), ('student3', 'lisi'), ('BBBBB', 'CCCCC'), (1, 2)])

可以循環打印

>>> for k,v in d1.items():

... print(k,v)

...

student2 AAAA

student3 lisi

BBBBB CCCCC

1 2



13、字典的循環

>>> for i in d1:

... print(i) //只打印key

...

student2

student3

BBBBB

1


>>> for i in d1:

... print(i,d1[i]) //把i當做key傳入到字典中查詢

...

student2 AAAA

student3 lisi

BBBBB CCCCC

1 2


14、for k,v in d1.items():和for i in d1:print(i,d1[i])的區別

第二種方式比較高效,因為第一種方式先把字典轉換為列表,在數據量大的情況下,會導致資源的浪費。

python字典操作