2016-11-29 6 views
-1

からのキーの中の辞書に分割:は、私は三つの辞書持っている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'....} 

を私は第3回1がこのように終わるように、三つの辞書を結合したいと思います:

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()} 

出力:あなたdict2の値が一意でない場合、あなたは何ができるか

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

は、次のように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

Hey ettananyは、動作するようですが、dict3に1つのタイムキーがある場合にのみ、私のdictに繰り返しキーがあります。 –

+0

私の答えの始めを見て、dict2の値が一意である辞書には同じキーを持つ複数の項目を含めることはできません。 – ettanany

+0

@AndreiCozma - 「私の辞書には繰り返しキーがある」いいえ、そうではありません。 – TigerhawkT3

関連する問題