用Python中另一个字典中的键的值替换一个字典中的键

2024-05-17 20:03:55 发布

您现在位置: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'}}

我正在寻找一种简单的方法,如何将dict2中的key值映射到dict1。你知道吗

结果字典应该是这样的

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

Tags: 方法key字典eth1词典dict1dict2dict3
2条回答

我认为实现这一点的一种方法就是为一个字典编写嵌套循环。(当然,您也可以使用列表理解,但我使用嵌套循环使其易于阅读)

    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

您可以使用嵌套的dict理解:

>>> 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中,对dict1中的键进行迭代。然后对每个键使用另一个dict理解,其中嵌套dict中的键被迭代:for k2 in dict1[k]。你知道吗

对于嵌套dicts中的每个键,键值对dict2[k][k2]: dict[k][k2]被添加到结果子字典中。最后将外键和生成的子字典添加到结果中。你知道吗

相关问题 更多 >