python - 从字典列表创建嵌套列表
问题描述
我有以下字典列表
[
{"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"]
]
如果有人对如何使其工作有任何想法,我将非常感谢您的提示。
解决方案
你可以试试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']]
推荐阅读
- java - 打破“得墨忒耳定律”和可能的解决方案
- c++ - 删除二叉树中的节点我哪里出错了?
- javascript - Service Worker 随机页面生成器
- unity3d - Unity 2020.1.0f1 缺少 UnityEngine.UI
- c++ - 分配两次 - c++
- gemfire - 通过 GemfireTemplate.query 方法使用 HINT 和 TRACE
- apache - Apache2.4 需要指令配置
- reactjs - 出现错误:有条件地调用 React Hook “useSpring”
- unity3d - 使用纹理将模型导入 Unity(不加载纹理)
- java - @WebMvcTest 创建名为“securityConfiguration”的 bean 时出错