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.