Anuar
Anuar

Reputation: 15

How to store outcome of a nested for loop as a nested dictionary in python?

from geopy.distance import geodesic

europe = {
    'Berlin': [52.5170365,  13.3888599],
    'Vienna': [48.2083537,  16.3725042],
    'Madrid': [40.4167047,  -3.7035825] 
}

usa = {
    'Boston'  : [42.3601,  -71.0589],
    'LA'      : [34.0522,  -118.2437],
    'Chicago' : [41.878,  -87.6298] 
}

dist = {}
for key_eu, city_eu in europe.items(): 
    for key_us, city_us in usa.items():
        dist[key_us] = geodesic(city_eu, city_us).km
dist 

The output is: {'Boston': 5484.653258486435, 'LA': 9383.686903608652, 'Chicago': 6741.855597482226}

I would like to save it as follows:

dist = {'Berlin': {'Boston' : 6096.945, 'LA' : 9331.657, 'Chicago' : 7102.591},
        'Vienna': {'Boston' : 6508.405, 'LA' : 9841.482, 'Chicago' : 7560.970}, 
        'Madrid': {'Boston' : 5484.65, 'LA' : 9383.686, 'Chicago' : 6741.855}}

Upvotes: 2

Views: 50

Answers (2)

Sash Sinha
Sash Sinha

Reputation: 22360

Consider using collections.defaultdict:

from geopy.distance import geodesic
from collections import defaultdict
from pprint import PrettyPrinter

europe = {
    'Berlin': [52.5170365, 13.3888599],
    'Vienna': [48.2083537, 16.3725042],
    'Madrid': [40.4167047, -3.7035825]
}

usa = {
    'Boston': [42.3601, -71.0589],
    'LA': [34.0522, -118.2437],
    'Chicago': [41.878, -87.6298]
}

dist = defaultdict(dict)
for key_eu, city_eu in europe.items():
    for key_us, city_us in usa.items():
        dist[key_eu][key_us] = round(geodesic(city_eu, city_us).km, 3)
dist = dict(dist)

PrettyPrinter(sort_dicts=False).pprint(dist)

Output:

{'Berlin': {'Boston': 6096.945, 'LA': 9331.657, 'Chicago': 7102.591},
 'Vienna': {'Boston': 6508.405, 'LA': 9841.482, 'Chicago': 7560.97},
 'Madrid': {'Boston': 5484.653, 'LA': 9383.687, 'Chicago': 6741.856}}

Upvotes: 2

go2nirvana
go2nirvana

Reputation: 1638

Just add another nested dict on each iteration.

europe = {
    'Berlin': [52.5170365,  13.3888599],
    'Vienna': [48.2083537,  16.3725042],
    'Madrid': [40.4167047,  -3.7035825] 
}

usa = {
    'Boston'  : [42.3601,  -71.0589],
    'LA'      : [34.0522,  -118.2437],
    'Chicago' : [41.878,  -87.6298] 
}

dist = {}
for key_eu, city_eu in europe.items(): 
    dist[key_eu] = {}
    for key_us, city_us in usa.items():
        dist[key_eu][key_us] = geodesic(city_eu, city_us).km
dist

Upvotes: 1

Related Questions