Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

python - 将值分组到字典中的列表(Grouping values to a list in dict)

While reading a csv file using csv.DictReader

(使用csv.DictReader读取csv文件时)

I get

(我懂了)

[{'id': 1, 'status1': '1', 'status2': '2', 'status3': '3' }]

How can I manuplate while reading or later to get:

(在阅读或以后阅读时如何处理:)

[{'id': 1, 'status': ['1', '2', '3']}]

TLDR;

(TLDR;)

I want to group similar fields into a list.

(我想将类似的字段分组到一个列表中。)

and/or - how can i do this in pandas pd.read_csv() too?

(和/或-我也如何在pd.read_csv()中做到这一点?)

Thanks in advance!

(提前致谢!)

  ask by sgp translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If it is certain that the only fields you want to group are those who end with digits, you can use a regex to identify them, and append their corresponding values to a list:

(如果确定要分组的唯一字段是以数字结尾的字段,则可以使用正则表达式来识别它们,并将其对应的值附加到列表中:)

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']}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...