不使用try填充字典 [英] fill a dictionary without using try except
问题描述
假设我有字典,我想用一些键和值来填充它,第一个字典为空,并假设我需要这个字典作为计数器,例如用这种方式对字符串中的一些键进行计数:
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
或者也许某些时候值应该是一个列表,而我需要以这种方式将一些值附加到值列表中:
Or maybe some times values should be a list and I need to append some values to a list of values I have this way:
myDic = {}
try:
myDic[desiredKey].append(desiredValue)
except KeyError:
myDic[desiredKey] = []
myDic[desiredKey].append(desiredValue)
对于不使用try except
部分的作品(两者)是否都有更好的替代?
Is there better alternarive for this works (both of them) that dont uses try except
section?
推荐答案
您可以使用collections.defaultdict()
,它允许您提供一个函数,该函数在每次访问丢失的键时都会被调用.
You can use collections.defaultdict()
which allows you to supply a function that will be called each time a missing key is accessed.
对于第一个示例,您可以将int
作为缺少的函数传递给它,该函数在首次访问时将被评估为0.
And for your first example you can pass the int
to it as the missing function which will be evaluated as 0 at first time that it gets accessed.
第二个可以通过list
.
示例:
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]})
这篇关于不使用try填充字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!