简体   繁体   English

Python 3:按字段元组对 dict 列表进行分组

[英]Python 3: Grouping a list of dict by a tuple of fields

I need to group a list of dict by a tuple of fields and write a function, which will do this for different sets of data.我需要按字段元组对 dict 列表进行分组并编写一个函数,该函数将对不同的数据集执行此操作。

For example: a list of dict:例如:字典列表:

[{'bnf_code': '0101010G0AAABAB',
 'items': 2,
  'practice': 'N81013',
  'bnf_name': 'Co-Magaldrox_Susp 195mg/220mg/5ml S/F',
  'nic': 5.98,
  'act_cost': 5.56,
  'quantity': 1000},
 {'bnf_code': '0101021B0AAAHAH',
  'items': 1,
  'practice': 'N81013',
  'bnf_name': 'Alginate_Raft-Forming Oral Susp S/F',
  'nic': 1.95,
  'act_cost': 1.82,
  'quantity': 500}]

and I want to groupby a tuple -> ('bnf_name', 'post_code')) .我想分组一个元组 -> ('bnf_name', 'post_code'))

I can't use pandas.我不能使用熊猫。

I've tried with below code but it raises a KeyError.我试过下面的代码,但它引发了一个 KeyError。

def group_by_field(data,fields):
    groups = {name: [] for name in fields}
    for script in data:
        for name in fields:
            groups[script[name]].append(script)
    return groups

Here is a function that does what you describe:这是一个执行您描述的功能的函数:

from collections import defaultdict
def group_by_field(data, fields):
    res = defaultdict(list)
    for d in data:
        key = tuple(d[f] for f in fields)
        res[key].append(d)
    return dict(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM