繁体   English   中英

python csv转换为嵌套字典

[英]python csv convert to nest dictionary

我的 csv 文件在下面

Uid,locate,category,act

Anna,NY,house,dance
Anna,LA,house,sing
Anna,CH,house,ride
John,NY,house,dance
John,LA,home,sing
John,CH,home,ride

我想创建字典就像


{'Uid': 'Anna', 'infos':[{'locate': 'NY', 'category': 'house', 'act': 'dance'},
                        {'locate': 'LA', 'category': 'house', 'act': 'sing'},
                        {'locate': 'CH', 'category': 'house', 'act': 'ride'}]
},
{'Uid': 'John', 'infos':[{'locate': 'NY', 'category': 'house', 'act': 'dance'},
                        {'locate': 'LA', 'category': 'home', 'act': 'sing'},
                        {'locate': 'CH', 'category': 'home', 'act': 'ride'}]
},

我的代码如下:

result = {}
with open('test.csv') as fp:
    reader = csv.DictReader(fp)
    for row in reader:
        result['test_uid'] = row['Uid']
        result["test_locate"] = row['locate']
        result["test_category"] = row['category']
        result["test_act"] = row['act']
print(result)

如何将信息数据附加到同一个人?

如何修复可以打印我想要的结果的代码?

请需要有人帮助。

请尝试以下操作:

payload = {}
# first let create a dict with uid as a key and a list of infos as a value.
with open('test.csv') as fp:
    reader = csv.DictReader(fp)
    for row in reader:
        data = {"locate": row['locate'], 'category': row['category'],
                          'act': row['act']}
        if row['Uid'] in payload.keys():
            payload[row['Uid']].append(data)
        else:
            payload[row['Uid']] = [data]

# reconstruct the payload to be list of dicts in the structure you want 
result = list(map(lambda uid, infos: {'Uid':uid, 'infos':infos}, payload.items()))

我会稍微更改生成的数据结构,以便更容易处理:

result = {}
with open('test.csv') as fp:
    reader = csv.DictReader(fp)
    for row in reader:
        if row['Uid'] not in result:
            result[row['Uid']] = [{
                'test_locate': row['locate'],
                'test_category': row['category'],
                'test_act': row['act']}]
        else:
            result[row['Uid']].append({
                'test_locate': row['locate'],
                'test_category': row['category'],
                'test_act': row['act']})
print(result)

您的输出看起来像一个列表,但您需要一本字典。 尝试这个:

result = {}
with open('test.csv') as fp:
    reader = csv.DictReader(fp)
    for row in reader:
        uid = row['Uid']
        del row['Uid']
        if uid in result:
            result[uid]['infos'].append(row)
        else:
            result[uid] = {'infos': [row]}

print(result)

您显示的结果实际上是一个字典列表。 如果这就是你想要的,那么:

result = []
with open('test.csv') as fp:
    reader = csv.DictReader(fp)
    infos = []
    last_uid = None
    for row in reader:
        uid = row['Uid']
        if uid != last_uid:
            if last_uid is not None:
                result.append({'Uid': last_uid, 'infos': infos})
                last_uid = uid
                infos = []
            last_uid = uid
        infos.append({'locate': row['locate'], 'category': row['category'], 'act': row['act']})
    if last_uid is not None:
        result.append({'Uid': last_uid, 'infos': infos})

暂无
暂无

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

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