Python dictionaries have keys and values. If we have two or more dictionaries to be merged a nested dictionary, then we can take the below approaches. Here year the dictionaries are given along with the new keys that will become a key in the nested dictionary.
Assigning keys
In this approach we will create a new empty dictionary. Then assigned the given dictionaries to each new key. The resulting dictionary will be a nested dictionary with the keys assigned.
Example
dictA = {'Sun': 1, 'Mon': 2} dictB = {'Tue': 3, 'Sun': 5} # Given Dictionaries print("DictA : ",dictA) print("DictB: ",dictB) # Using key access and dict() res = dict() res['Netsed_dict_1'] = dictA res['Netsed_dict_2'] = dictB # printing result print("Netsed Dictionary: \n" ,res)
Running the above code gives us the following result −
Output
DictA : {'Sun': 1, 'Mon': 2} DictB: {'Tue': 3, 'Sun': 5} Netsed Dictionary: {'Netsed_dict_1': {'Sun': 1, 'Mon': 2}, 'Netsed_dict_2': {'Tue': 3, 'Sun': 5}}
Using zip
The Jeep function can convert keys and dictionaries into to a Tuple. Then we apply the dict function to get the final result which is a dictionary containing the new keys as well as the input dictionaries.
Example
dictA = {'Sun': 1, 'Mon': 2} dictB = {'Tue': 3, 'Sun': 5} # Given Dictionaries print("DictA : ",dictA) print("DictB: ",dictB) # Using zip dict_keys = ['Netsed_dict_1','Netsed_dict_2'] all_dicts = [dictA,dictB] res = dict(zip(dict_keys,all_dicts)) # printing result print("Netsed Dictionary: \n" ,res)
Running the above code gives us the following result −
Output
DictA : {'Sun': 1, 'Mon': 2} DictB: {'Tue': 3, 'Sun': 5} Netsed Dictionary: {'Netsed_dict_1': {'Sun': 1, 'Mon': 2}, 'Netsed_dict_2': {'Tue': 3, 'Sun': 5}}