【问题标题】:Create a nested list from list of dictionaries从字典列表创建嵌套列表
【发布时间】:2021-09-15 13:25:57
【问题描述】:

我有以下词典列表

[ 
{"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"]
]

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

【问题讨论】:

    标签: python json python-3.x list dictionary


    【解决方案1】:

    你可以用 Pandas 来做(l 是你的列表):

    import pandas as pd
    df=pd.DataFrame(l)
    gr=df.groupby('Control')['Message'].apply(list)
    res=[[i]+gr[i] for i in gr.index]
    
    print(res)
    

    输出:

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

    【讨论】:

      【解决方案2】:

      使用itertools.groupby 您可以实现这一目标

      from itertools import groupby
      from operator import itemgetter
      
      values = [
          {"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"}
      ]
      
      key = itemgetter("Control")
      
      result = [[key, *[i['Message'] for i in val]]
                for key, val in groupby(sorted(values, key=key), key=key)]
      

      或者collections.defaultdict

      from collections import defaultdict
      result = defaultdict(list)
      for row in values:
          result[row["Control"]].append(row['Message'])
      result = [[key, *val] for key, val in result.items()]
      

      【讨论】:

        【解决方案3】:

        你可以试试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']]
        

        【讨论】:

          猜你喜欢
          • 2020-10-22
          • 1970-01-01
          • 1970-01-01
          • 2021-11-20
          • 2021-04-19
          • 2018-01-16
          • 1970-01-01
          • 2021-04-04
          相关资源
          最近更新 更多