python中字典的常用函数_Python字典dict常用方法函数实例
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é)果Joe
print(dict.get('hobby'))
#結(jié)果None
print(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é)果
name
age
height
#相同效果的遍歷如下:
for key in dict.keys():
print(key)
#
字典的遍歷,遍歷value
for vlaue in dict.values():
print(vlaue)
#結(jié)果
Joe
18
60
字典的遍歷,遍歷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 Joe
age 18
height 60
#輸出為字符串的另一種方式
for i in dict:
print(i,dict[i])
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
本文標(biāo)題: Python字典dict常用方法函數(shù)實(shí)例
本文地址: http://www.cppcns.com/jiaoben/python/362759.html
總結(jié)
以上是生活随笔為你收集整理的python中字典的常用函数_Python字典dict常用方法函数实例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 和平精英可以在电脑上玩吗
- 下一篇: sqlserver模糊查询不用like_