【发布时间】:2016-11-14 04:47:36
【问题描述】:
我正在我的程序中生成一个嵌套字典。生成后,我想遍历该字典,并检查字典键和值。
程序代码
这是我要迭代的字典,其值包含另一个字典。
main_dict = {101: {1234: [11111,11111],5678: [44444,44444]},
102: {9100: [55555,55555],1112: [77777,88888]}}
我正在读取一个 csv 文件并将内容存储在这本字典中。像这样:
Input.csv -
lineno,item,total
101,1234,11111
101,1234,11111
101,5678,44444
101,5678,44444
102,9100,55555
102,9100,55555
102,1112,77777
102,1112,88888
这是输入的 csv 文件。我正在阅读这个 csv 文件,我想知道一个独特的项目总共重复了多少次?
对于我正在做的那些事情:
for line in reader:
if line[0] in main_dict:
if line[1] in main_dict[line[0]]:
main_dict[line[0]][line[1]].append(line[2])
else:
main_dict[line[0]].update({line[1]:[line[2]]})
else:
main_dict[line[0]] = {line[1]:[line[2]]}
print main_dict
上述程序的输出:
{101: {1234: [11111,11111],5678: [44444,44444]},
102: {9100: [55555,55555],1112: [77777,88888]}}
但我在这一行遇到以下错误-
if line[1] in main_dict[line[0]]:
IndexError: list index out of range
main_dict的迭代-
for key,value in main_dict.iteritems():
f1 = open(outputfile + op_directory +'/'+ key+'.csv', 'w')
writer1 = csv.DictWriter(f1, delimiter=',', fieldnames = fieldname)
writer1.writeheader()
if type(value) == type({}):
for k,v in value.iteritems():
if type(v) == type([]):
set1 = set(v)
for se in set1:
writer1.writerow({'item':k,'total':se,'total_count':v.count(se)})
我想知道迭代此类字典的最佳方法?
有时我会得到正确的结果,就像上面的字典一样,但很多时候我都会遇到这个错误,我错过了什么?
提前致谢!
【问题讨论】:
-
您缺少检查
main_dict[line[0]]是否存在 -if not main_dict[line[0]]: #do whatever you find right to -
可能其中一行缺少信息。好像不完整。
-
你能给我们一个失败的输入 csv 吗?我怀疑你在某处有一个空行。
-
@dmitryro- 仅在 for 循环之后,我正在检查 main_dict 中是否存在 line[0],如果不存在,则添加整行。
-
@Dean Fenster- 不是空行问题。我添加了 if line: then only operation get perform
标签: python dictionary