使用Python从CSV文件创建嵌套字典 [英] Creating a nested dictionary from a CSV file with Python

查看:242
本文介绍了使用Python从CSV文件创建嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件"input.csv",其中包含以下数据.

I have a a csv file "input.csv" which has the following data.

UID,BID,R
U1,B1,4
U1,B2,3
U2,B1,2

我希望以上内容看起来像下面的字典;按UID作为键进行分组,将BID和R作为嵌套字典值进行分组.

I want the above to look like the following dictionary; group by the UID as they key and BID and R as a nested dictionary value.

{"U1":{"B1":4, "B2": 3}, "U2":{"B1":2}}

我有以下代码:

new_data_dict = defaultdict(str)
with open("input.csv", 'r') as data_file:
    data = csv.DictReader(data_file, delimiter=",")
    headers = next(data)
    for row in data:
        new_data_dict[row["UID"]] += {row["BID"]:int(row["R"])}

上面抛出了一个明显的错误

The above throws an obvious error of

TypeError: cannot concatenate 'str' and 'dict' objects

有没有办法做到这一点?

Is there a way to do this?

推荐答案

使用常规的dict(),您可以使用get()初始化一个新的子字典,然后将其填充.

Using the regular dict() you can use get() to initialize a new sub-dict and fill it afterwards.

import csv

new_data_dict = {}
with open("data.csv", 'r') as data_file:
    data = csv.DictReader(data_file, delimiter=",")
    for row in data:
        item = new_data_dict.get(row["UID"], dict())
        item[row["BID"]] = int(row["R"])

        new_data_dict[row["UID"]] = item

print new_data_dict

此外,由于自动检测到标头并将其从结果中剥离,因此您对next(data)的调用是多余的.

Also, your call to next(data) was superfluous as the headers were automatically detected and stripped from the result.

这篇关于使用Python从CSV文件创建嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆