将dict列表转换为dict列表列表

时间:2014-08-09 06:42:51

标签: python list dictionary

我有一个字典列表。

l = [{'row':1}, {'row':2}, {'row':1}, {'row':3}, {'row':1}]

我希望输出为:

x = [[{'row':1}, {'row':1}, {'row':1}], [{'row':2}], [{'row':3}]]

我想要那些“行”值相同的词典列表   我怎么能用python做到这一点?

2 个答案:

答案 0 :(得分:5)

使用itertools.groupby

>>> import itertools
>>>
>>> l = [{'row':1}, {'row':2}, {'row':1}, {'row':3}, {'row':1}]
>>> row = lambda d: d['row']
>>> [list(grp) for _, grp in itertools.groupby(sorted(l, key=row), key=row)]
[[{'row': 1}, {'row': 1}, {'row': 1}], [{'row': 2}], [{'row': 3}]]

注意您需要将已排序的列表传递给groupby

替代,不需要使用collection.defaultdict进行排序:

>>> from collections import defaultdict
>>>
>>> l = [{'row':1}, {'row':2}, {'row':1}, {'row':3}, {'row':1}]
>>> ret = defaultdict(list)
>>> for d in l:
...     ret[d['row']].append(d)
...
>>> ret.values() # list(d.values())   in Python 3.x
[[{'row': 1}, {'row': 1}, {'row': 1}], [{'row': 2}], [{'row': 3}]]

正如shx2评论的那样,替代解决方案的结果将是任意的。如果您想要排序结果,请使用以下表格:

>>> [ret[key] for key in sorted(ret)]
[[{'row': 1}, {'row': 1}, {'row': 1}], [{'row': 2}], [{'row': 3}]]

答案 1 :(得分:0)

x_dict = {}
for d in l:
    x_dict[d['row']] = x_dict.get(d['row'], []) + [d]
x = [x_dict[key] for key in sorted(x_dict.keys())]