2016-11-29 79 views
-1

未来密钥中的字典我有3点字典:拆分从2个不同的其他字典

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'....} 

我想,这样的3TH一个结束这样的3个词典结合:

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. 

我已经尝试了从这里的合并函数Merge dictionaries retaining values for duplicate keys,但我有一个糟糕的时间在所有名称中平分dict3。

+3

您的输出是不可能的。字典必须具有唯一的密钥。 – DeepSpace

回答

1

只有dict2的值是唯一的(因为它们将成为结果字典的关键字),所需的输出才有可能。在这种情况下,你可以使用这个:

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

输出:

>>> 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'} 

如果您dict2的价值观是不是唯一可以做的就是使用列表存储res_dict值如下:

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]] 

输出:

>>> res_dict 
{'Andrew': ['ID03', 'ID01'], 'Kevin': ['ID02']} 
+0

嘿ettanany,这似乎工作,但只有当你有一个时间键在dict3,我的字典有重复的键虽然 –

+0

看看我的答案的开头,我提到它的工作原理只有当dict2的值是唯一的,因为字典不能包含具有相同密钥的多个项目。 – ettanany

+0

@AndreiCozma - “我的字典有重复的键”不,它不。 – TigerhawkT3