Issue
I can't figure out how to create a dictionary of dictionaries for how many fruit I bought for several days.
Given a text file that looks like this
0 apple
0 orange
1 apple
1 apple
1 strawberry
2 orange
The first column is which day the fruit what bought on, and the second is which fruit was bought on that day.
I want to return a dictionary of dictionaries, where the keys are the days, and the value is another dictionary that keeps track of how many of that fruit was bought on that day.
{0: {'apple': 1, 'orange': 1, 'strawberry': 0}, 1: {'apple': 2, 'orange': 0, 'strawberry': 1}, 2: {'apple': 0, 'orange': 1, 'strawberry': 0}}
Im trying to do this without list comprehension or any imports, as I don't quite understand those. Any help would be great!
Solution
Okay so I have a pretty naive solution without imports and list comprehensions.
final = {}
with open('file.txt', 'r') as f:
prev = None
for line in f.readlines():
key, value = line.split()
if prev == None:
prev = key
d = {'apple': 0, 'orange': 0, 'strawberry': 0}
elif prev != key:
final[int(prev)] = d
prev = key
d = {'apple': 0, 'orange': 0, 'strawberry': 0}
d[value] = d.get(value, 0)+1
final[int(prev)] = d
print(final)
All I did is created a temporary inner dictionary, then updated it until next value is not reached, then if next value is reached then I have added the previous dictionary to the final one.
Output:
{0: {'apple': 1, 'orange': 1, 'strawberry': 0}, 1: {'apple': 2, 'orange': 0, 'strawberry': 1}, 2: {'apple': 0, 'orange': 1, 'strawberry': 0}}
Hope it helps :)
Answered By - Debdut Goswami
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.