[英]What's the cleanest (most Pythonic) way of creating a dictionary with list values from a sequence?
I have a collection that looks like this: 我有一个看起来像这样的集合:
stuff = [('key1', 1), ('key2', 2), ('key3', 3),
('key1', 11), ('key2', 22), ('key3', 33),
('key1', 111), ('key2', 222), ('key3', 333),
]
# Note: values aren't actually that nice. That would make this easy.
I want to turn it into a dictionary that looks like this: 我想把它变成这样的字典:
dict_stuff = {'key1': [1, 11, 111],
'key2': [2, 22, 222],
'key3': [3, 33, 333],
}
What's the nicest way to convert this data? 转换此数据的最佳方法是什么? The first method that comes to mind is:
我想到的第一种方法是:
dict_stuff = {}
for k,v in stuff:
dict[k] = dict.get(k, [])
dict[k].append(v)
Is that the cleanest way to do this? 这是最干净的方法吗?
You can make use of dict.setdefault
, like this 您可以像这样使用
dict.setdefault
。
dict_stuff = {}
for key, value in stuff:
dict_stuff.setdefault(key, []).append(value)
It says that, if the key
doesn't exist in the dictionary, then use the second parameter as the default value for it, otherwise return the actual value corresponding to the key
. 它说,如果字典中不存在该
key
,则使用第二个参数作为其默认值,否则返回与该key
对应的实际值。
We also have a built-in dict
class, which helps you deal with cases like this, called collections.defaultdict
. 我们还有一个内置的
dict
类,可帮助您处理类似情况的称为collections.defaultdict
。
from collections import defaultdict
dict_stuff = defaultdict(list)
for key, value in stuff:
dict_stuff[key].append(value)
Here, if the key
doesn't exist in the defaultdict
object, the factory function passed to the defaultdict
constructor will be called to create the value object. 在这里,如果
key
在defaultdict
对象中不存在,则传递给defaultdict
构造函数的工厂函数将被调用以创建value对象。
There is defaultdict
in the collections
lib. collections
库中有defaultdict
。
>>> from collections import defaultdict
>>> dict_stuff = defaultdict(list) # this will make the value for new keys become default to an empty list
>>> stuff = [('key1', 1), ('key2', 2), ('key3', 3),
... ('key1', 11), ('key2', 22), ('key3', 33),
... ('key1', 111), ('key2', 222), ('key3', 333),
... ]
>>>
>>> for k, v in stuff:
... dict_stuff[k].append(v)
...
>>> dict_stuff
defaultdict(<type 'list'>, {'key3': [3, 33, 333], 'key2': [2, 22, 222], 'key1': [1, 11, 111]})
stuff_dict = {}
for k, v in stuff:
if stuff_dict.has_key(k):
stuff_dict[k].append(v)
else:
stuff_dict[k] = [v]
print stuff_dict
{'key3': [3, 33, 333], 'key2': [2, 22, 222], 'key1': [1, 11, 111]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.