dist = {'Berlin': {'Boston' : 6096.945, 'LA' : 9331.657, 'Chicago' : 7102.591},
'Vienna': {'Boston' : 6508.405, 'LA' : 9841.482, 'Chicago' : 7560.970},
'London': {'Boston' : 5484.658, 'LA' : 9383.686, 'Chicago' : 6741.855}}
time = {'Berlin': {'Boston' : 6, 'LA' : 9, 'Chicago' : 7},
'Vienna': {'Boston' : 6, 'LA' : 9, 'Chicago' : 7},
'London': {'Boston' : 5, 'LA' : 8, 'Chicago' : 6}}
How to merge two dictionaries to get values in a list as follows:
new_dict = {'Berlin': {'Boston' : [6096.95, 6], 'LA' : [9331.65, 9], 'Chicago' : [7102.59, 7]},
'Vienna': {'Boston' : [6508.40, 6], 'LA' : [9841.48, 9], 'Chicago' : [7560.97, 7]},
'London': {'Boston' : [5484.65, 5], 'LA' : [9383.68, 8], 'Chicago' : [6741.85, 6]}}
Thank you in advance!
You can solve that with a 2-level dict-comprehension
result = {
city_from: {city_to: [distance_val, time[city_from][city_to]]
for city_to, distance_val in cities_to.items()}
for city_from, cities_to in dist.items()
}
Equivalent of a classic 2 for-loop solution
result = defaultdict(dict) # from collections import defaultdict
for city_from, cities_to in dist.items():
for city_to, distance_val in cities_to.items():
result[city_from][city_to] = [distance_val, time[city_from][city_to]]
Not too elegant, but works:
def combine_dicts(a, b):
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
combine_dicts(a[key], b[key])
else:
a[key] = [a[key], b[key]]
else:
a[key] = [a[key], b[key]]
return a
Note: this function will change the original dict a
, if you wan't to leave the original dict unchanged, pass copies to func
from copy import deepcopy
combined = combine_dicts(deepcopy(dist), deepcopy(time))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.