Python字典dict常用方法函數實例
dict={’name’:’Joe’,’age’:18,’height’:60}
clear,清空
dict.clear()#運行結果{}
pop,移除指定key的鍵值對并返回vlaue(如果沒有該key,可返回指定值),popitem,默認移除最后一個鍵值對
print(dict.pop(’age’))print(dict)#結果18,{’name’: ’Joe’, ’height’: 60}print(dict.pop(’agea’,’erro’))print(dict)#結果erro,{’name’: ’Joe’, ’age’: 18, ’height’: 60}print(dict.popitem())print(dict)#結果(’height’, 60),{’name’: ’Joe’, ’age’: 18}
del,刪除字典的另一種方式
del dict[’age’]print(dict)#結果{’name’: ’Joe’, ’height’: 60}
get,返回指定鍵的值,如果值不在字典中返回default值,等同于dict.__getitem__(’name’)
print(dict.get(’name’))#結果Joeprint(dict.get(’hobby’))#結果Noneprint(dict.get(’hobby’,’basketball’))#結果basketball
setdefault,和get()類似, 但如果鍵不存在于字典中,將會添加鍵并將值設為default
print(dict.setdefault(’hobby’))print(dict)#結果None,{’name’: ’Joe’, ’age’: 18, ’height’: 60, ’hobby’: None}print(dict.setdefault(’hobby’,’basketball’))print(dict)#結果basketball,{’name’: ’Joe’, ’age’: 18, ’height’: 60, ’hobby’: ’basketball’}
update,更新字典,有key則更新該key對應的vlaue,沒有則新增
dict.update({’age’:20})print(dict)#結果{’name’: ’Joe’, ’age’: 20, ’height’: 60}dict.update({’hobby’:’run’})print(dict)#結果{’name’: ’Joe’, ’age’: 18, ’height’: 60, ’hobby’: ’run’}
fromkeys,創建新字典,以seq為key,vlaue為字典的初始值
seq = (’a’, ’b’, ’c’)print(dict.fromkeys(seq))#結果{’a’: None, ’b’: None, ’c’: None}print(dict.fromkeys(seq,’oh’))#結果{’a’: ’oh’, ’b’: ’oh’, ’c’: ’oh’}
字典的打印,取值等
print(dict.items())print(dict.values())print(dict.keys())#結果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)#結果nameageheight#相同效果的遍歷如下:for key in dict.keys():print(key)#字典的遍歷,遍歷valuefor vlaue in dict.values():print(vlaue)#結果Joe1860
字典的遍歷,遍歷item
#10.1輸出為元組的方式for item in dict.items():print(item)#結果(’name’, ’Joe’)(’age’, 18)(’height’, 60)#10.2輸出為字符串的方式for key,vlaue in dict.items():print(key,vlaue)#結果name Joeage 18height 60#輸出為字符串的另一種方式for i in dict:print(i,dict[i])
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: