Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python csv转换为嵌套字典_Python_Csv - Fatal编程技术网

python csv转换为嵌套字典

python csv转换为嵌套字典,python,csv,Python,Csv,我的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'},

我的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)

如何将infos数据附加到同一个人

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


需要有人帮忙。

请尝试以下操作:

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})

你的输出是什么?哇!这个数据结构比我想要的要简单,谢谢你的想法!!!