Python字典dict常用方法函數(shù)實(shí)例
dict={’name’:’Joe’,’age’:18,’height’:60}
clear,清空
dict.clear()#運(yùn)行結(jié)果{}
pop,移除指定key的鍵值對并返回vlaue(如果沒有該key,可返回指定值),popitem,默認(rèn)移除最后一個(gè)鍵值對
print(dict.pop(’age’))print(dict)#結(jié)果18,{’name’: ’Joe’, ’height’: 60}print(dict.pop(’agea’,’erro’))print(dict)#結(jié)果erro,{’name’: ’Joe’, ’age’: 18, ’height’: 60}print(dict.popitem())print(dict)#結(jié)果(’height’, 60),{’name’: ’Joe’, ’age’: 18}
del,刪除字典的另一種方式
del dict[’age’]print(dict)#結(jié)果{’name’: ’Joe’, ’height’: 60}
get,返回指定鍵的值,如果值不在字典中返回default值,等同于dict.__getitem__(’name’)
print(dict.get(’name’))#結(jié)果Joeprint(dict.get(’hobby’))#結(jié)果Noneprint(dict.get(’hobby’,’basketball’))#結(jié)果basketball
setdefault,和get()類似, 但如果鍵不存在于字典中,將會添加鍵并將值設(shè)為default
print(dict.setdefault(’hobby’))print(dict)#結(jié)果None,{’name’: ’Joe’, ’age’: 18, ’height’: 60, ’hobby’: None}print(dict.setdefault(’hobby’,’basketball’))print(dict)#結(jié)果basketball,{’name’: ’Joe’, ’age’: 18, ’height’: 60, ’hobby’: ’basketball’}
update,更新字典,有key則更新該key對應(yīng)的vlaue,沒有則新增
dict.update({’age’:20})print(dict)#結(jié)果{’name’: ’Joe’, ’age’: 20, ’height’: 60}dict.update({’hobby’:’run’})print(dict)#結(jié)果{’name’: ’Joe’, ’age’: 18, ’height’: 60, ’hobby’: ’run’}
fromkeys,創(chuàng)建新字典,以seq為key,vlaue為字典的初始值
seq = (’a’, ’b’, ’c’)print(dict.fromkeys(seq))#結(jié)果{’a’: None, ’b’: None, ’c’: None}print(dict.fromkeys(seq,’oh’))#結(jié)果{’a’: ’oh’, ’b’: ’oh’, ’c’: ’oh’}
字典的打印,取值等
print(dict.items())print(dict.values())print(dict.keys())#結(jié)果dict_items([(’name’, ’Joe’), (’age’, 18), (’height’, 60)])dict_values([’Joe’, 18, 60])dict_keys([’name’, ’age’, ’height’])
字典的遍歷,遍歷key
for i in dict:print(i)#結(jié)果nameageheight#相同效果的遍歷如下:for key in dict.keys():print(key)#字典的遍歷,遍歷valuefor vlaue in dict.values():print(vlaue)#結(jié)果Joe1860
字典的遍歷,遍歷item
#10.1輸出為元組的方式for item in dict.items():print(item)#結(jié)果(’name’, ’Joe’)(’age’, 18)(’height’, 60)#10.2輸出為字符串的方式for key,vlaue in dict.items():print(key,vlaue)#結(jié)果name Joeage 18height 60#輸出為字符串的另一種方式for i in dict:print(i,dict[i])
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Java基于redis和mysql實(shí)現(xiàn)簡單的秒殺(附demo)2. ASP.NET MVC視圖頁使用jQuery傳遞異步數(shù)據(jù)的幾種方式詳解3. 如何用python識別滑塊驗(yàn)證碼中的缺口4. 三道java新手入門面試題,通往自由的道路--鎖+Volatile5. SpringBoot+SpringCache實(shí)現(xiàn)兩級緩存(Redis+Caffeine)6. php讀取xml中某個(gè)元素的內(nèi)容(PHP5以上才支持)7. AJAX實(shí)現(xiàn)省市縣三級聯(lián)動效果8. 關(guān)于HTML5的img標(biāo)簽9. python多線程爬取西刺代理的示例代碼10. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)
