【发布时间】:2016-11-20 14:21:26
【问题描述】:
我有一个 CSV,其中第一列有许多重复值,第二列是映射到第三列中的值的预定代码,例如:
1, a, 24
1, b, 13
1, c, 30
1, d, 0
2, a, 1
2, b, 12
2, c, 82
2, d, 81
3, a, 04
3, b, 23
3, c, 74
3, d, 50
我正在尝试从 CSV 创建字典字典,结果如下:
dict 1 = {'1':{'a':'24', 'b':'13', 'c':'30','d':'0'},
'2':{'a':'1', 'b':'12', 'c':'82','d':'81'},
... }
我的代码可以很好地创建键值,但是结果值字典都是空的(尽管一些打印语句显示它们不在运行过程中)...
with open(file, mode='rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
dict1 = {} # creates main dict
for row in reader: # iterates through the rows of the csvfile
if row[0] in dict1:
dict2[row[1]] = row[2] # adds another key, value to dict2
else:
dict1[row[0]] = {} # creates a new key entry for the new dict1 key
dict2 = {} # creates a new dict2 to start building as the value for the new dict1 key
dict2[row[1]] = row[2] # adds the first key, value pair for dict2
【问题讨论】:
-
您没有指定
dict2成为dict1的一部分。
标签: python csv dictionary nested