我想创建一个字典如下 -
{'a':[1, 2, 3, 4, 5], 'b':[1, 3, 5], 'c':[2, 3, 5]}
我的实现方式是
mydict = dict()
letters = ['a', 'b', 'a', 'c', 'a']
#please mark the list has multiple occurence of a,
#hence I would want to check if a key with 'a' exists. Please do not advise to make the list unique.
for l in letters:
if not mydict.get(l):
mydict[l] = <values from another place via some filter>
else:
mydict[l].append(<values from another dict>)
有没有更好的方法来做到这一点?
最佳答案
是的,您可以使用 defaultdict :
示例代码:
»»» from collections import defaultdict
»»» mydict = defaultdict(list)
»»» letters = ['a', 'b', 'a', 'c', 'a']
»»» for l in letters:
....: mydict[l].append('1')
....:
»»» mydict
Out[15]: defaultdict(<type 'list'>, {'a': ['1', '1', '1'], 'c': ['1'], 'b': ['1']})
如果您需要将内容初始化为更高级的东西,您可以指定您自己的构造函数作为 defaultdict
的第一个参数。不过,将特定于上下文的参数传递给该构造函数可能会很棘手。
关于python - 使用具有列表作为其值的唯一键创建一个 python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16695514/