-1

I have 3 dictionaries :

dict1 = {'Name1':'Andrew','Name2':'Kevin'....'NameN':'NameN'}- this would have maximum 20 names
dict2 = {'Travel':'Andrew','Footbal':'Kevin',...'Nhobby':'NameN'}- this would have as many names as there are in dict1
dict3 = {'Travel':'ID01','Footbal':'ID02','Travel':'ID03','Photo':'ID04','Footbal':'ID05','Photo':'ID06','Climbing':'ID07'....}

I would like to combine the 3 dictionaries so that the 3th one ends up this way:

 dict3 = {'Andrew':'ID01','Kevin':'ID02','Andrew':'ID03','Kevin':'ID04','Kevin':'ID05','Kevin':'ID06','Andrew':'ID07',....}. Basically the hobbies that are in the dict 2 will be kept while the remaining hobbies will be split among the total number of names with a +1 in the case of an uneven number of hobbies.

I have tried the merge function from here Merge dictionaries retaining values for duplicate keys but I have a bad time splitting the dict3 equally among all names.

Community
  • 1
  • 1
Andrei Cozma
  • 950
  • 3
  • 9
  • 14

1 Answers1

1

The output that you want is possible only if dict2's values are unique (because they will become keys of the resulted dictionary). In this case, you can use this:

res_dict = {val: dict3[dict2.keys()[dict2.values().index(val)]] for val in dict1.values()}

Output:

>>> dict1 = {'Name1': 'Andrew', 'Name2': 'Kevin'}
>>> dict2 = {'Travel': 'Andrew', 'Footbal': 'Kevin'}
>>> dict3 = {'Travel': 'ID01', 'Footbal': 'ID02'}

>>> res_dict = {val: dict3[dict2.keys()[dict2.values().index(val)]] for val in dict1.values()}
>>> res_dict
{'Andrew': 'ID01', 'Kevin': 'ID02'}

What you can do if your dict2's values are not unique is to use lists to store res_dict values as follows:

dict1 = {'Name1': 'Andrew', 'Name2': 'Kevin'}
dict2 = {'Travel': 'Andrew', 'Footbal': 'Kevin', 'Photo': 'Andrew'}
dict3 = {'Travel': 'ID01', 'Footbal': 'ID02', 'Photo': 'ID03'}

res_dict = {}

for val in dict1.values():
    val_keys = []
    for key in dict2.keys():
        if dict2[key] == val:
            val_keys.append(key)
    for item in val_keys:
        if dict2[item] in res_dict:
            res_dict[dict2[item]].append(dict3[item])
        else:
            res_dict[dict2[item]] = [dict3[item]]

Output:

>>> res_dict
{'Andrew': ['ID03', 'ID01'], 'Kevin': ['ID02']}
ettanany
  • 19,038
  • 9
  • 47
  • 63
  • Hey ettanany, that seems to work but only when you have one time keys in dict3 , my dict has repetitive keys though – Andrei Cozma Nov 29 '16 at 09:17
  • Take a look at the beginning of my answer, I mentioned that it works only if values of dict2 are unique, because a dictionary can not contain multiple items with the same key. – ettanany Nov 29 '16 at 09:18
  • @AndreiCozma - "my dict has repetitive keys" No it doesn't. – TigerhawkT3 Nov 29 '16 at 09:21
  • @AndreiCozma Please take a look at my edited answer, and let me know it helps you/ – ettanany Nov 29 '16 at 10:27