Iterate through a dictionary and create new dictionary from multiple dictionaries

I’m trying to create a new dictionary from three dictionaries, where the ‘fields’ key isn’t duplicated and LON and LAX are the top level keys.

dict1 = {"LON": {'fields': 
                {'country': 'England', 
                 'weather': 'rainy'}},
         "LAX": {'fields': 
                {'country': 'America', 
                 'weather': 'sunny'}}}

dict2 = {'fields': {'color' : 'red', 'movie' : 'yes'}}

dict3 = {"LON": {'fields': 
                {'time-zone': 'CET', 
                 'description': ''}},
         "LAX": {'fields': 
                {'time-zone': 'UTC', 
                 'description': ''}}}

The new dictionary would look like this:

**EDIT In original post, dict3 ‘field’ values were missing from newdict, I’ve since corrected this.

newdict = {"LON": {'fields': 
                  {'country': 'England', 
                   'weather': 'rainy',
                   'color' : 'red',
                   'movie' : 'yes'
                   'time-zone': 'CET', 
                   'description': ''}}
           "LAX": {'fields': 
                  {'country': 'America', 
                   'weather': 'sunny',
                   'color' : 'red'
                   'movie' : 'yes'
                   'time-zone': 'UTC', 
                   'description': ''}}}

I’ve tried the following solution, but it doesn’t get rid of duplicate ‘fields’, and I can’t work out how to get dict2 merged in. Any help or ideas for a different approach would be much appreciated as I’m not getting very far on this one.

result = {}
for key in (dict1.keys() | dict3.keys()):
   if key in dict1: result.setdefault(key, []).append(dict1[key])
   if key in dict3: result.setdefault(key, []).append(dict3[key])
print(result)

Answer

You can loop through key value pair in dictionary using for loop and using Update method you can add key value pair from dict2 to dict1.

The update() method inserts the specified items to the dictionary.

The specified items can be a dictionary, or an iterable object with key value pairs.

 for k,v in dict1.items():
        for a, b in v.items():
            for x , y in dict2['fields'].items():            
                dict1[k][a].update({x : y})
    print(dict1)

Leave a Reply

Your email address will not be published. Required fields are marked *