Python Forum

Full Version: Dictionaries in dictionaries
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey guys!
I have a question about dictionaries, namely how I can create a nested dictionary from a loop.
The problem is as follows. I have a farm and several clients buying fruit and vegetables from me.

Smith Apple 100
Davis Apple 70
Smith Potato 40
Smith Apple 10
Brown Cucumber 30
Davis Cucumber 90
Miller Potato 50
Brown Potato 30
Brown Potato 50
Davis Apple 30
Miller Cucumber 40


The first column is the name of the client. The second one is the type of product he/she buys. The third one is the number of sold kilograms.

Here, I have to create a nested dictionary using the data above. The output should be like this:
{'Smith': {'Apple': 110, 'Potato': 40}, 'Davis': {'Apple': 100, 'Cucumber': 90}, Brown: {'Cucumber': 30, 'Potato': 80}, Miller: {'Potato': 50, 'Cucumber': 40}}
I've been trying to crack this problem for two days Sad The best I could get so far is to create a dictionary with names as key. I think when I at least know how to create a value in the form of a dictionary I can try further. Wall

Thank you in advance!
What does your current code look like?
It looks raw Confused

fin = open('input.txt', 'r', encoding='utf8')
fout = open('output.txt', 'w', encoding='utf8')
data = list(map(lambda x: x.split(), fin.readlines()))
myDict = {}

for i in data:
    myDict[i[0]] = {i[1]: int(i[2])}

print(myDict, file=fout)
I know that my innerdictionary gets rewritten everyt time there is a new value in the loop. So, that's what I get in the end:
{'Smith': {'Apple': 10}, 'Davis': {'Apple': 30}, 'Brown': {'Potato': 50}, 'Miller': {'Cucumber': 40}}
(Dec-12-2018, 09:24 PM)misha Wrote: [ -> ]
for i in data:
    myDict[i[0]] = {i[1]: i[2]}

Instead of setting the dict's value to a dict, set the sub-dict's value, and then make sure there's a sub-dict you can access. Also, use better variable names lol
for key, sub_key, value in data:
    if key not in myDict:
        myDict[key] = {}
    myDict[key][sub_key] = value
Also...
(Dec-12-2018, 09:24 PM)misha Wrote: [ -> ]data = list(map(lambda x: x.split(), fin.readlines()))
You can use str.split directly:
data = list(map(str.split, fin.readlines()))
Thank you Angel