亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

我們都知道,在 Python 的字典里邊,如果 key 不存在的話,通過 key 去取值是會報錯的。

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

如果我們在取不到值的時候不報錯而是給定一個默認(rèn)值的話就友好多了。

初始化的時候設(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è)定默認(rèn)值(setdefault(key, default)) 

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

因此,如果你在循環(huán)里邊給一個 key 重復(fù)設(shè)定默認(rèn)值的話,那么也只會第一次設(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è)定默認(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é)

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

相關(guān)文章

最新評論