Python 将值分组到dict中的列表

Python 将值分组到dict中的列表,python,python-3.x,Python,Python 3.x,使用csv.DictReader读取csv文件时 我明白了 [{'id': 1, 'status1': '1', 'status2': '2', 'status3': '3' }] 我如何在阅读时或以后使用manuplate获得: [{'id': 1, 'status': ['1', '2', '3']}] TLDR; 我想将类似字段分组到一个列表中 和/或-如何在pandas pd.read_csv()中执行此操作 提前谢谢 如果确定要分组的字段只有以数字结尾的字段,则可以使用正则表达式来

使用csv.DictReader读取csv文件时

我明白了

[{'id': 1, 'status1': '1', 'status2': '2', 'status3': '3' }]
我如何在阅读时或以后使用manuplate获得:

[{'id': 1, 'status': ['1', '2', '3']}]
TLDR; 我想将类似字段分组到一个列表中

和/或-如何在pandas pd.read_csv()中执行此操作


提前谢谢

如果确定要分组的字段只有以数字结尾的字段,则可以使用正则表达式来标识这些字段,并将其相应的值附加到列表中:

import re

def compact_dict(d):
    compact = {}
    for key, value in d.items():
        # a group containing anything, followed by at least one digit
        m = re.match(r'(.*)\d+', key)  
        if m:
            # the key that we use is the original one without the final digits
            compact.setdefault(m.group(1), []).append(value)
        else:
            # not part of a group of similar keys, we just store the key:value pair
            compact[key] = value
    return compact

data = [{'id': 1, 'status1': '1', 'status2': '2', 'status3': '3' }]
out = [compact_dict(d) for d in data]
print(out)
# [{'id': 1, 'status': ['1', '2', '3']}]

请定义“相似”。如“状态1”、“状态2”等。。进入“状态”有什么相似之处?这些“相似”键是否总是类似于
status1
,或者可以是
statusA
或其他什么,或者是否有更多的变量类似于
other1
other2
?还有其他变量类似于other1和other2。目前,蒂埃里的回答给出了所需的输出