Thursday, 8 August 2013

Nested dictionary in python

Nested dictionary in python

Hi This is my first question on Stack Overflow. I have the following data
where first column are ID, second column are category, third column is
items and fourth column is price. I am try to find each ID's spend sum by
category(column2 from left): A sample output will be: like below. However,
I am stuck on the elif statement and says it has keyError:'A': I really do
not know what is wrong. If anyone knows please help me out. Thanks very
much.
***sample output***
Spending by B fuel - 19.60 grocery - 11.42



A|groceries|cereal|15.50 A|groceries|milk|14.75 A|tobacco|cigarettes|25.00
A|fuel|gasoline|54.90 B|fuel|propane|19.60 B|groceries|apple|11.42
C|tobacco|cigarettes|25.00



for line in fileinput.input(fo1):
#print line
line =str.rstrip(line)
line = line.split('|')
print line[0],line[1]
(name,category,items,price)=line
if line[0] in report2 and line[1] in report2:
report2[line[0]][line[1]] += float(price)
elif line[1] in report2[line[0]]:
report2[line[0]][line[1]]+=float(price)
else:
report2[line[0]][line[1]]=float(price)
print report2.keys
print report2.items()

No comments:

Post a Comment