简体   繁体   中英

How to compare two nested dictionaries with the same keys and update values with a condition in python?

d1 = {'Berlin': {'Boston' : 9, 'LA' : 7, 'Chicago' : 1},
      'Vienna': {'Boston' : 5, 'LA' : 2, 'Chicago' : 8}, 
      'London': {'Boston' : 8, 'LA' : 6, 'Chicago' : 5}}

d2 = {'Berlin': {'Boston' : 8, 'LA' : 9, 'Chicago' : 4},
      'Vienna': {'Boston' : 3, 'LA' : 1, 'Chicago' : 5}, 
      'London': {'Boston' : 5, 'LA' : 8, 'Chicago' : 8}}

I would like to update the values in d1 if the values in d2 smaller than in d1 to get a new dictionary d:

d = {'Berlin': {'Boston' : 8, 'LA' : 7, 'Chicago' : 1},
     'Vienna': {'Boston' : 3, 'LA' : 1, 'Chicago' : 5}, 
     'London': {'Boston' : 5, 'LA' : 6, 'Chicago' : 5}}

This works as per your requirement (take min of dict items by iterating them together via zip and re-combine as a dict again, put it as value with same k as the key again):

d1 = {'Berlin': {'Boston' : 9, 'LA' : 7, 'Chicago' : 1},
      'Vienna': {'Boston' : 5, 'LA' : 2, 'Chicago' : 8}, 
      'London': {'Boston' : 8, 'LA' : 6, 'Chicago' : 5}}

d2 = {'Berlin': {'Boston' : 8, 'LA' : 9, 'Chicago' : 4},
      'Vienna': {'Boston' : 3, 'LA' : 1, 'Chicago' : 5}, 
      'London': {'Boston' : 5, 'LA' : 8, 'Chicago' : 8}}

>>> {k: dict([min(i, j) for i, j in zip(d1[k].items(), d2[k].items())]) for k in d1.keys()}
{'Berlin': {'Boston': 8, 'LA': 7, 'Chicago': 1},
 'Vienna': {'Boston': 3, 'LA': 1, 'Chicago': 5},
 'London': {'Boston': 5, 'LA': 6, 'Chicago': 5}}

This data seems like it would be better as a dataframe (basically a table) instead of a nested dict.

Once you create the input dataframes, you just need to combine them using a function that selects the minimal value for each cell. Here's a way to do that straight from the documentation :

import numpy as np
import pandas as pd

df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

df_new = df1.combine(df2, np.minimum)
print(df_new)

Output:

         Berlin  Vienna  London
Boston        8       3       5
LA            7       1       6
Chicago       1       5       5

If you need to get it back to a dict, you can use DataFrame.to_dict() :

d = df_new.to_dict()

Which becomes:

{'Berlin': {'Boston': 8, 'LA': 7, 'Chicago': 1},
 'Vienna': {'Boston': 3, 'LA': 1, 'Chicago': 5},
 'London': {'Boston': 5, 'LA': 6, 'Chicago': 5}}

PS I'm not an expert at Pandas

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM