2017-02-24 132 views
0

值我有2個字典在Python在一個字典替換鍵與鍵從另一個詞典在Python

dict1={'_Switch1': {'portB': '20', 'portA': '10'}, '_Switch2': {'portB': '200', 'portA': '100'}} 

dict2={'_Switch1': {'portB': 'eth1/2', 'portA': 'eth1/1'}, '_Switch2': {'portB': 'eth2/2', 'portA': 'eth2/1'}} 

我找AA簡單的方法,我怎麼能映射dict2鍵的值到dict1。

產生的字典應該是這個樣子

dict3={'_Switch1': {'eth1/2': '20', 'eth1/1: '10'}, '_Switch2': {'eth2/2': '200', 'eth2/1': '100'}} 

回答

0

您可以使用嵌套的字典理解:在dict1

>>> dict1={'_Switch1': {'portB': '20', 'portA': '10'}, '_Switch2': {'portB': '200', 'portA': '100'}} 
>>> dict2={'_Switch1': {'portB': 'eth1/2', 'portA': 'eth1/1'}, '_Switch2': {'portB': 'eth2/2', 'portA': 'eth2/1'}} 
>>> {k: {dict2[k][k2]: dict1[k][k2] for k2 in dict1[k]} for k in dict1} 
{'_Switch1': {'eth1/1': '10', 'eth1/2': '20'}, '_Switch2': {'eth2/2': '200', 'eth2/1': '100'}} 

在上面for k in dict1迭代的鑰匙。然後,對於每個鍵,在嵌套字典中的鍵被迭代時使用另一個詞典理解:for k2 in dict1[k]

對於嵌套字典中的每個鍵值對dict2[k][k2]: dict[k][k2]被添加到生成的子字典中。最後,將外鍵和生成的子字典添加到結果中。

0

我認爲完成此操作的一種方法是簡單地爲一個字典編寫嵌套循環。 (當然,您也可以使用列表理解,但我使用嵌套循環以方便閱讀)

dict1={'_Switch1': {'portB': '20', 'portA': '10'}, '_Switch2': {'portB': '200', 'portA': '100'}} 

    dict2={'_Switch1': {'portB': 'eth1/2', 'portA': 'eth1/1'}, '_Switch2': {'portB': 'eth2/2', 'portA': 'eth2/1'}} 

    #This will be the new dictionary 
    dict3 = {} 

    for key in dict1: 
     tmpdict = {} 
     for key_child, item in dict1[key].iteritems(): 
      tmpdict[dict2[key][key_child]] = item 
     dict3[key] = tmpdict 
相關問題