欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中如何給字典設(shè)置默認(rèn)值

 更新時(shí)間:2023年02月21日 14:15:44   作者:Looooking  
這篇文章主要介紹了Python中如何給字典設(shè)置默認(rèn)值問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

Python字典設(shè)置默認(rèn)值

我們都知道,在 Python 的字典里邊,如果 key 不存在的話,通過(guò) key 去取值是會(huì)報(bào)錯(cuò)的。

>>> aa = {'a':1, 'b':2}
>>> aa['c']
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
KeyError: 'c'

如果我們?cè)谌〔坏街档臅r(shí)候不報(bào)錯(cuò)而是給定一個(gè)默認(rèn)值的話就友好多了。

初始化的時(shí)候設(shè)定默認(rèn)值(defaultdict 或 dict.fromkeys)

>>> from collections import defaultdict
>>> aa = defaultdict(int)
>>> aa['a'] = 1
>>> aa['b'] = 2
>>> aa
defaultdict(<class 'int'>, {'a': 1, 'b': 2})
>>> aa['c']
0
>>> aa
defaultdict(<class 'int'>, {'a': 1, 'b': 2, 'c': 0})
>>> aa = dict.fromkeys('abc', 0)
>>> aa
{'a': 0, 'b': 0, 'c': 0}

defaultdict(default_factory) 中的 default_factory 也可以傳入自定義的匿名函數(shù)之類的喲。 

>>> aa = defaultdict(lambda : 1)
>>> aa['a']
1

獲取值之前的時(shí)候設(shè)定默認(rèn)值(setdefault(key, default)) 

這里有個(gè)比較特殊的點(diǎn):只要對(duì)應(yīng)的 key 已經(jīng)被設(shè)定了值之后,那么對(duì)相同 key 再次設(shè)置默認(rèn)值就沒(méi)用了。

因此,如果你在循環(huán)里邊給一個(gè) key 重復(fù)設(shè)定默認(rèn)值的話,那么也只會(huì)第一次設(shè)置的生效。

>>> aa = {'a':1, 'b':2}
>>> aa
{'a': 1, 'b': 2}
>>> aa.get('c')
>>> aa.setdefault('c', 'hello')
'hello'
>>> aa.get('c')
'hello'
>>> aa
{'a': 1, 'b': 2, 'c': 'hello'}
>>> aa.setdefault('c', 'world')
'hello'
>>> aa.get('c')
'hello'

獲取值的時(shí)候設(shè)定默認(rèn)值(dict.get(key, default))

>>> aa = {'a':1, 'b':2}
>>> aa
{'a': 1, 'b': 2}
>>> aa['c']
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
KeyError: 'c'
>>> aa.get('c')
>>> aa
{'a': 1, 'b': 2}
>>> aa.get('c', 'hello')
'hello'
>>> aa.get('b')
2

python創(chuàng)建帶默認(rèn)值的字典

防止keyerror創(chuàng)建帶默認(rèn)值的字典

from collections import defaultdict
data = collections.defaultdict(lambda :[])

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論