Suppose I have dictionary and I want to fill that with some keys and values , first dictionary is empty and suppose I need this dictionary for a counter for example count some keys in a string I have this way:
myDic = {}
try :
myDic[desiredKey] += 1
except KeyError:
myDic[desiredKey] = 1
或者有时值应该是一个列表,我需要将一些值附加到一个值列表中,我可以这样做:
myDic = {}
try:
myDic[desiredKey].append(desiredValue)
except KeyError:
myDic[desiredKey] = []
myDic[desiredKey].append(desiredValue)
?
最佳答案
您可以使用collections.defaultdict()
来提供一个函数,该函数将在每次访问丢失的键时调用。
。
第二个可以通过int
。
例子:
from collections import defaultdict
my_dict = defaultdict(int)
>>> lst = [1,2,2,2,3]
>>> for i in lst:
... my_dict[i]+=1
...
>>>
>>> my_dict
defaultdict(<type 'int'>, {1: 1, 2: 3, 3: 1})
>>> my_dict = defaultdict(list)
>>>
>>> for i,j in enumerate(lst):
... my_dict[j].append(i)
...
>>> my_dict
defaultdict(<type 'list'>, {1: [0], 2: [1, 2, 3], 3: [4]})
关于python - 不使用try填充字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35612666/