我有一个看起来像这样的集合:
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.
我想把它变成一个看起来像这样的字典:
dict_stuff = {'key1': [1, 11, 111],
'key2': [2, 22, 222],
'key3': [3, 33, 333],
}
转换此数据最好的方法是什么?想到的第一种方法是:
dict_stuff = {}
for k,v in stuff:
dict[k] = dict.get(k, [])
dict[k].append(v)
这是最干净的方法吗?
答案 0 :(得分:2)
您可以使用dict.setdefault
,就像这样
dict_stuff = {}
for key, value in stuff:
dict_stuff.setdefault(key, []).append(value)
它表示,如果字典中不存在key
,则使用第二个参数作为默认值,否则返回与key
对应的实际值。
我们还有一个内置的dict
类,可帮助您处理此类案例,称为collections.defaultdict
。
from collections import defaultdict
dict_stuff = defaultdict(list)
for key, value in stuff:
dict_stuff[key].append(value)
这里,如果key
对象中不存在defaultdict
,则会调用传递给defaultdict
构造函数的工厂函数来创建值对象。
答案 1 :(得分:1)
defaultdict
lib中有collections
。
>>> 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]})
答案 2 :(得分:0)
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]}