python 嵌套字典 初始化,使用Python从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

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值