Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

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}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...