Python字典dict常用方法函數(shù)實(shí)例
dict={’name’:’Joe’,’age’:18,’height’:60}
clear,清空
dict.clear()#運(yùn)行結(jié)果{}
pop,移除指定key的鍵值對(duì)并返回vlaue(如果沒有該key,可返回指定值),popitem,默認(rèn)移除最后一個(gè)鍵值對(duì)
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()類似, 但如果鍵不存在于字典中,將會(huì)添加鍵并將值設(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對(duì)應(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])
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP中格式化時(shí)間短日期補(bǔ)0變兩位長(zhǎng)日期的方法2. 告別AJAX實(shí)現(xiàn)無刷新提交表單3. ASP中if語句、select 、while循環(huán)的使用方法4. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法5. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera6. asp批量添加修改刪除操作示例代碼7. PHP設(shè)計(jì)模式中工廠模式深入詳解8. HTML DOM setInterval和clearInterval方法案例詳解9. 讀大數(shù)據(jù)量的XML文件的讀取問題10. ASP實(shí)現(xiàn)加法驗(yàn)證碼
