【问题标题】:Grouping Python dictionaries in hierarchical form with multiple keys?使用多个键以分层形式对 Python 字典进行分组?
【发布时间】:2022-12-03 08:15:55
【问题描述】:

这是我的字典列表:

[{'subtopic': 'IAM',
  'topic': 'AWS',
  'attachments': ['{"workflow.name": "aws_iam_policies_info","workflow.parameters": {"region": "us-east"}}'],
  'text': 'Sure! I can help with AWS IAM policies info'},
 {'subtopic': 'ECS',
  'topic': 'AWS',
  'attachments': ['{"workflow.name": "aws_ecs_restart_service","workflow.parameters": {"region": "us-east"}}'],
  'text': 'Sure! I can help with restarting AWS ECS Service'},
 {'subtopic': 'EC2',
  'topic': 'AWS',
  'attachments': ['{"workflow.name": "aws_ec2_create_instance","workflow.parameters": {"region": "us-east"}}'],
  'text': 'Sure, I can help creating an EC2 machine'},
 {'subtopic': 'EC2',
  'topic': 'AWS',
  'attachments': ['{"workflow.name": "aws_ec2_security_group_info","workflow.parameters": {"region": "us-east"}}'],
  'text': 'Sure, I can help with various information about AWS security groups'},
 {'subtopic': 'S3',
  'topic': 'AWS',
  'attachments': ['{"workflow.name": "aws_s3_file_copy","workflow.parameters": {"region": "us-west"}}'],
  'text': 'Sure, I can help you with the process of copying on S3'},
 {'subtopic': 'GitHub',
  'topic': 'AWS',
  'attachments': ['{"workflow.name": "view_pull_request","workflow.parameters": {"region": "us-west"}}'],
  'text': 'Sure, I can help with GitHub pull requests'},
 {'subtopic': 'Subtopic Title',
  'topic': 'Topic Title',
  'attachments': [],
  'text': 'This is another fact'},
 {'subtopic': 'Subtopic Title',
  'topic': 'Topic Title',
  'attachments': [],
  'text': 'This is a fact'}]

我想按主题和子主题分组以获得最终结果:

{
    "AWS": {
        "GitHub": {
            'attachments': ['{"workflow.name": "view_pull_request","workflow.parameters": {"region": "us-west"}}'],
            'text': ['Sure, I can help with GitHub pull requests']
            },
        "S3": {
            'attachments': ['{"workflow.name": "aws_s3_file_copy","workflow.parameters": {"region": "us-west"}}'],
            'text': ['Sure, I can help you with the process of copying on S3']
            },
        "EC2": {
            'attachments': ['{"workflow.name": "aws_ec2_create_instance","workflow.parameters": {"region": "us-east"}}',
                            '{"workflow.name": "aws_ec2_security_group_info","workflow.parameters": {"region": "us-east"}}'],
            'text': ['Sure, I can help creating an EC2 machine', 
                     'Sure, I can help with various information about AWS security groups']
        },
        "ECS": {
            'attachments': ['{"workflow.name": "aws_ecs_restart_service","workflow.parameters": {"region": "us-east"}}'],
            'text': ['Sure! I can help with restarting AWS ECS Service']
        },
        "IAM": {
            'attachments': ['{"workflow.name": "aws_iam_policies_info","workflow.parameters": {"region": "us-east"}}'],
            'text': ['Sure! I can help with AWS IAM policies info']
        }
        
    },
    "Topic Title": {
        "Subtopic Title": {
            'attachments': [],
            'text': ['This is another fact']
        }
    }
} 

我在用:

groups = ['topic', 'subtopic', "text", "attachments"]
groups.reverse()

def hierachical_data(data, groups):
    g = groups[-1]
    g_list = []
    for key, items in itertools.groupby(data, operator.itemgetter(g)):
        g_list.append({key:list(items)})
    groups = groups[0:-1]
    if(len(groups) != 0):
        for e in g_list:
            for k, v in e.items():
                e[k] = hierachical_data(v, groups)
    return g_list

print(hierachical_data(filtered_top_facts_dicts, groups))

但是哈希列表出错。 请告知如何将我的 json 转换为所需的格式。

【问题讨论】:

    标签: python python-3.x dictionary python-itertools itertools-groupby


    【解决方案1】:

    要按主题和子主题对列表中的项目进行分组,您可以结合使用 itertools 模块中的 groupby() 函数和 collections 模块中的 defaultdict() 对象。

    这是您如何执行此操作的示例:

    from itertools import groupby
    from collections import defaultdict
    
    # List of dicts to group by topic and subtopic
    data = [
        {'subtopic': 'IAM', 'topic': 'AWS', ...},
        {'subtopic': 'ECS', 'topic': 'AWS', ...},
        ...
    ]
    
    # Group the items by topic and subtopic
    grouped_data = defaultdict(lambda: defaultdict(dict))
    for key, items in groupby(data, key=lambda x: (x['topic'], x['subtopic'])):
        topic, subtopic = key
        items = list(items)
        attachments = [item['attachments'] for item in items]
        text = [item['text'] for item in items]
        grouped_data[topic][subtopic] = {'attachments': attachments, 'text': text}
    
    # Print the grouped data
    print(grouped_data)
    

    此代码将按主题和子主题字段对字典列表中的项目进行分组,并使用生成的分组创建嵌套字典。最终结果将类似于您在问题中提供的结果。

    我希望这有帮助!

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多