程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Defaultdict, a dictionary that supplements default values in Pythons collections package

編輯:Python

Sometimes when you access a key in a dictionary , Key may not exist , So it needs to be checked , If no default value is found, it is sometimes necessary to add a default value .

A one-step approach is to use collections In bag defaultdict, It creates a dictionary that automatically sets the default values , Returns the value of the key if it exists , If the key does not exist, the default value is returned and the key value pair is added to the dictionary .

defaultdict The parameter to be passed in is a function , If it is int Then the initial value is 0, If it is list The initial value is an empty list , Of course, you can also pass in custom functions .

from collections import defaultdict
adict=defaultdict(int)
adict['a']=2
print(adict)
print(adict['b'])
print(adict)
bdict=defaultdict(lambda :'hhh')
print(bdict['c'])

Output :

defaultdict(<class 'int'>, {
'a': 2})
0
defaultdict(<class 'int'>, {
'a': 2, 'b': 0})
hhh

You can find , It is similar to the dictionary setdefault Very similar , But it saves more space , For example, to set the default value to an empty list ,setdefault The way to write is xxdict.setdefault(xxkey,[]), No matter what xxkey Whether there is , Empty lists are created , But if you use xxdict=defaultdict(list), The empty list will be created only when the key cannot be found , So it saves more space .

defaultdict On initialization , You can also pass in the initial dictionary through the second parameter :

cdict=defaultdict(list,{
'c':'aaa'})
print(cdict)

Output :

defaultdict(<class 'list'>, {
'c': 'aaa'})

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved