pythonnested

How do I iterate through a dictionary which has nested dictionaries to compare each nested dictionary to an input dictionary?


Example:

input_dict = {1:23, 2:34, 3:45, 4:56}
nested_dict = {'one':{1:23}, 'two':{1:23, 2:34}, 'three':{1:23, 2:34, 5:67}}

The ultimate goal is to compare input_dict to each of the nested dictionaries in nested_dict and create a list of the keys of nested_dict where any of the input_dict keys and values completely match all of the nested_dict keys and values. It should ignore anything extra in input_dict.

In the example above, the output would be:

['one', 'two']

I found a way to compare two dictionaries with:

all(
  key in input_dict and nested_dict[key] == input_dict[key] 
  for key in nested_dict
)

Solution

  • You were close. Iterate the nested_dict items and check each nested dictionary. Collect the keys of the ones that all match the input_dict:

    input_dict = {1:23, 2:34, 3:45, 4:56}
    nested_dict = {'one':{1:23}, 'two':{1:23, 2:34}, 'three':{1:23, 2:34, 5:67}}
    
    keys = [key for key, nested in nested_dict.items()
            if all(k in input_dict and nested[k] == input_dict[k] for k in nested)]
    
    print(keys)
    

    Output:

    ['one', 'two']