2016-11-06 155 views
0

的值替換嵌套鍵目前我有兩個字典 我想字典中的另一個字典

d1 = {1:{1: 2.0,2: 1.5,3: 5.0}, 
     2:{1: 7.5,2: 6.0,3: 1.0}} 
d2 = {1: 'a', 2: 'b', 3: 'c'} 
expected output: {1:{'a': 2.0,'b': 1.5,'c': 5.0}, 
        2:{'a': 7.5,'b': 6.0,'c': 1.0}} 

可悲的是這兩個dictionarys都充滿了其他字典的值來改變內部密鑰很多數據,並且需要很長時間才能在d1上迭代,並調用一個迭代d2的方法來替換d1中的鍵。

是否有可能在更快的時間內更改內鍵,值對? 我發現了一個可能性,以取代簡單的字典的鍵:

d = {'x':1,'y':2,'z':3} 
d1 = {'x':'a','y':'b','z':'c'} 
d = {d1[k]:v for k,v in d.items()} 

output: {'a': 1, 'c': 3, 'b': 2} 

但與嵌套的字典。

所以現在我不知道如何解決我的問題。 也許你們中的一個人可以幫助我。

回答

1

您可以使用嵌套字典理解爲做到這一點:

>>> d1 = {1:{1: 2.0,2: 1.5,3: 5.0}, 
...  2:{1: 7.5,2: 6.0,3: 1.0}} 
>>> d2 = {1: 'a', 2: 'b', 3: 'c'} 
>>> {a: {d2[k]: v for k, v in d.items()} for a, d in d1.items()} 
{1: {'a': 2.0, 'c': 5.0, 'b': 1.5}, 2: {'a': 7.5, 'c': 1.0, 'b': 6.0}} 

OR,使用簡單for環路:

>>> for _, d in d1.items(): # Iterate over the "d1" dict 
...  for k, v in d.items(): # Iterate in nested dict 
...   d[d2[k]] = v # Add new key based on value of "d2" 
...   del d[k] # Delete old key in nested dict 
... 
>>> d1 
{1: {'a': 2.0, 'c': 5.0, 'b': 1.5}, 2: {'a': 7.5, 'c': 1.0, 'b': 6.0}} 

第二條本辦法將更新原d1字典,其中作爲第一方法將創建新的dict對象。

+0

謝謝它的作品完美 – pat92

0

我認爲答案是使用我之前遇到的字典zip。

你可以用zip解決你的問題,就像在這個答案中一樣。雖然你的需要一個內在的水平,所以它稍有不同。

Map two lists into a dictionary in Python

d1 = {1:{1: 2.0,2: 1.5,3: 5.0}, 
     2:{1: 7.5,2: 6.0,3: 1.0}} 
d2 = {1: 'a', 2: 'b', 3: 'c'} 

d1_edited = {} # I prefer to create a new dictionary than edit the existing whilst looping though existing 
newKeys = d2.values() # e.g. ['a', 'b', 'c'] 
for outer in d1.keys(): # e.g. 1 on first iteration 
    newValues = d1[outer] # e.g. e.g. {1: 2.0,2: 1.5,3: 5.0} on first iteration 
    newDict = dict(zip(newKeys,newValues)) # create dict as paired up keys and values 
    d1_edited[outer] = newDict # assign dictionary to d1_edited using the unchanged outer key. 

print d1_edited 

輸出

{1: {'a': 1, 'c': 3, 'b': 2}, 2: {'a': 1, 'c': 3, 'b': 2}} 
+0

謝謝它的作品完美 – pat92

相關問題