Python从CSV文件创建嵌套字典 [英] Python Creating A Nested Dictionary From CSV File

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

问题描述

所以我有一个csv文件input.csv,它有以下数据。

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

我想让上面看起来像下面的字典;按照UID分组作为他们的键,BID和R作为嵌套字典值。

  {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)
数据行:
new_data_dict [ row [UID]] + = {row [BID]:int(row [R])}


b $ b

上述引发了一个明显的错误:

  TypeError:不能连接'str' b $ b  

有办法吗? 使用常规的 dict()您可以使用 get()初始化一个新的子字典,然后填充它。

  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)的调用是多余的,因为标头被自动检测和删除从结果。


So 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

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

I have the below code:

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?? Any help will be appreciated.

解决方案

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

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

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

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