首页 > 解决方案 > 从字典列表创建嵌套列表

问题描述

我有以下字典列表

[ 
{"Control":"[check11] Enable MFA", "Message":"account x1"},
{"Control":"[check11] Enable MFA", "Message":"account x2"},
{"Control":"[check12] Rotate keys", "Message":"account x1"},
{"Control":"[check12] Rotate keys", "Message":"account x2"}
]

我想获得“控制”和所有控制“消息”的唯一值,所以它看起来像这样

[
["[check11] Enable MFA", "account x1", "account x2"],
["[check12] Rotate keys", "account x1", "account x2"]
]

如果有人对如何使其工作有任何想法,我将非常感谢您的提示。

标签: pythonjsonpython-3.xlistdictionary

解决方案


你可以试试itertools.groupby

from itertools import groupby

l = [ 
{"Control":"[check11] Enable MFA", "Message":"account x1"},
{"Control":"[check11] Enable MFA", "Message":"account x2"},
{"Control":"[check12] Rotate keys", "Message":"account x1"},
{"Control":"[check12] Rotate keys", "Message":"account x2"}
]

l.sort(key = lambda x: x["Control"]) # this sorting is required
# beacuse if the sequence is (0,0,1,1,0,2,2)
# groupby will group like ((0,0), (1,1), (0), (2,2))

output = []
for grp_name, group in groupby(l, key= lambda x: x["Control"]):
    output.append([grp_name, *[g['Message'] for g in group]])
    
print(output)
[['[check11] Enable MFA', 'account x1', 'account x2'], 
['[check12] Rotate keys', 'account x1', 'account x2']]

推荐阅读