Python Forum
combining dicts into one dict when not all keys are in both dicts
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
combining dicts into one dict when not all keys are in both dicts
#2
Your dictionaries are defined incorrectly but other than that, the code seems to be functioning as expected.

dict1 = {'AFG': 'Afghanistan', 'ALB': 'Albania', 'ALG': 'Algeria'}
dict2 = {'AFG': {'Gold': 0, 'Silver': 0, 'Bronze': 2, 'Total': 2},
		'ALG': {'Gold': 5, 'Silver': 4, 'Bronze': 8, 'Total': 17}}

def switch_to_full_name(dict1,dict2):
    if isinstance(dict1, dict) and isinstance(dict2, dict):
        for k in dict1:
            if k in dict2:
                comb_dict = dict(zip(dict1.values(), dict2.values()))
        return comb_dict
    else:
        return "Input must be a dictionary"

print (switch_to_full_name (dict1, dict2))


Output:
{'Afghanistan': {'Gold': 0, 'Silver': 0, 'Bronze': 2, 'Total': 2}, 'Albania': {'Gold': 5, 'Silver': 4, 'Bronze': 8, 'Total': 17}}
Reply


Messages In This Thread
RE: combining dicts into one dict when not all keys are in both dicts - by BashBedlam - May-12-2021, 02:44 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020