什么';使用序列中的列表值创建字典的最干净(最具python风格)的方法是什么?

什么';使用序列中的列表值创建字典的最干净(最具python风格)的方法是什么?,python,dictionary,Python,Dictionary,我有一个像这样的收藏: 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. dic

我有一个像这样的收藏:

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],
              }
我想把它变成这样的字典:

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)
这是最干净的方法吗?

你可以像这样利用它

dict_stuff = {}
for key, value in stuff:
    dict_stuff.setdefault(key, []).append(value)
它表示,如果字典中不存在
,则使用第二个参数作为默认值,否则返回与
对应的实际值

我们还有一个内置的
dict
类,名为


在这里,如果
defaultdict
对象中不存在
,则将调用传递给
defaultdict
构造函数的工厂函数来创建值对象。

集合
库中存在
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]})
>>从集合导入defaultdict
>>>dict_stuff=defaultdict(list)#这将使新键的值默认为空列表
>>>stuff=[('key1',1),('key2',2),('key3',3),
…('key1',11),('key2',22),('key3',33),
…('key1',111),('key2',222),('key3',333),
...          ]
>>> 
>>>对于材料中的k,v:
...     dict_stuff[k].追加(v)
... 
>>>口述材料
defaultdict(,{'key3':[3,33,333],'key2':[2,22,222],'key1':[1,11,111]})

请注意,如果以后您想关闭默认dict的“默认”行为,只需将
default\u factory
属性设置为
None
。e、 g.
dict\u stuff.default\u factory=None
如果
stuff
保证按“键”排序,我会使用
itertools.groupby
。由于情况似乎并非如此,
collections.defaultdict
可能是您的下一个最佳选择(如答案所示)
has\u key
已被弃用,如果stuff\u dict:k,您只需执行