2016-11-29 57 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

相關問題