如何通过其中一个键值将词典列表分组到词典的子列表中?

时间:2014-05-11 21:48:16

标签: python list dictionary

如何通过其中一个键值将词典列表分组到词典的子列表中?

例如,我想将此词典列表更改为词典的子列表

lst = [{'A':12,'B':32,'ID':333},{'Z':32,'C':43,'ID':111},{'D':43,'J':31,'ID':222},{'a':32,'b':31,'ID':222},{'D':43,'ID':333},{'a':89,'d':31,'ID':222},{'C':83,'ID':111}]


Desired_lst = [[{'A':12,'B':32,'ID':333},{'D':43,'ID':333}],[{'Z':32,'C':43,'ID':111},{'C':83,'ID':111}],[{'D':43,'J':31,'ID':222},{'a':32,'b':31,'ID':222},{'a':89,'d':31,'ID':222}]]

我已经尝试了以下功能,但这不起作用,因为我不确定如何应用groupby或排序到词典。

from itertools import groupby
from operator import itemgetter


Desired_List = [list(grp) for key, grp in itertools.groupby(sorted(lst, key=operator.itemgetter(['ID'])),key=operator.itemgetter(['ID'))]

1 个答案:

答案 0 :(得分:3)

我认为您当前代码的问题在于您如何调用itemgetter。参数应该是用于访问对象的键,没有任何容器。您正在传递一个列表,这不是一个合法的字典键。尝试:

keyfunc = operator.itemgetter("ID")
Desired_List = [list(grp) for key, grp in itertools.groupby(sorted(lst, key=keyfunc),
                                                            key=keyfunc)]