Python Forum
Nested Dictionaries with Lists - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Nested Dictionaries with Lists (/thread-16317.html)



Nested Dictionaries with Lists - BriHaug - Feb-23-2019

I have seen similar threads related to creating nested dictionaries, but I'm still having trouble with this particular code. My goal is to use nested dictionaries to sort locations with seasons with values. Keep in mind that I created dummy lists to represent what I'm working with. I am not able to use matrices as I am going to have to remove random bits of information (not set them equal to zero, but actually remove them). I am also applying this code to literally hundreds of thousands of points, so hard-coding is not an option. Here is the code I have come up with so far:

Seasons = ['Spring','Summer','Fall','Winter']
Locations = ['Paris','London','San Francisco']
Number = [[10, 34, 56, 7], [9000, 40, 21, 17], [43, 628, 906, 1]]

FinalDict = dict()
TempDict = dict()

for j in Seasons:
    for i in Locations:
        m = Seasons.index(j)
        n = Locations.index(i)
        TempDict[j] = Number[n][m]
        FinalDict[i] = TempDict

print FinalDict
This is what my dictionary looks like now:

{'Paris': {'Spring': 43, 'Fall': 906, 'Winter': 1, 'Summer': 628}, 'San Francisco': {'Spring': 43, 'Fall': 906, 'Winter': 1, 'Summer': 628}, 'London': {'Spring': 43, 'Fall': 906, 'Winter': 1, 'Summer': 628}}
My goal is to have my dictionary look something like this:

{'Paris': {'Spring': 10, 'Fall': 56, 'Winter': 7, 'Summer': 34}, 'San Fransisco': {'Spring': 43, 'Fall': 906, 'Winter': 1, 'Summer': 628}, 'London': {'Spring': 9000, 'Fall': 21, 'Winter': 17, 'Summer': 40}}
Any help would be greatly appreciated Blush

Thanks!

I'm working with Python 2.7. Forgot to mention.


RE: Nested Dictionaries with Lists - ichabod801 - Feb-23-2019

You need to create a new TempDict for each location. You only have one TempDict now, so all your sub-dictionaries look the same because they are the same.

Edit: I would also redo your for loops using zip to avoid the backtracking to indexes:

for location, location_data in zip(Locations, Number):
    TempDict = {}
    for season, number in zip(Seasons, location_data):
        TempDict[season] = number
    FinalDict[location] = TempDict