首页 > 解决方案 > python从列表中搜索dict中的两个键

问题描述

我有以下字典:

{
    "neighbors": [
        {
            "5142_2_IpIf1002": "10.10.160.141",
            "8700_ipif_1002": "10.10.160.142"
        },
        {
            "5142_2_IpIf1006": "10.10.160.181",
            "5170_ipif_1006": "10.10.160.182"
        },
        {
            "5160_1_IpIf1005": "10.10.160.177",
            "5170_ipif_1005": "10.10.160.178"
        },
        {
            "5160_1_IpIf3337": "10.10.160.125",
            "8700_IpIf3337": "10.10.160.126"
        },
        {
            "8700_ipif_1001": "10.10.160.129",
            "5160_1_IpIf1001": "10.10.160.130"
        },
        {
            "8700_ipif_1003": "10.10.160.169",
            "5170_ipif_1003": "10.10.160.170"
        },
        {
            "8700_ipif_1004": "10.10.160.173",
            "5170_ipif_1004": "10.10.160.174"
        }
    ]
}

以及以下列表:

hostnames = ['8700', '5170', '5142_2']

在上面的字典中,我只查找包含至少两个列表元素的条目,以查找我想在网络中找到的路径的 LLDP 邻居。

import json

hostnames = ['8700', '5170', '5142_2']

with open('ip_list.json', 'r') as f:
    data = json.load(f)


for element in data["neighbors"]:
    for h in hostnames:
        if h in str(element.keys()):
            print('{} - {}'.format(element.keys(), element.values()))

这段代码为“元素”字典中的一个条目解决了这个问题,但这不是我需要的。

所以在这种情况下,我希望程序只从 json 文件中打印出以下条目:

"5142_2_IpIf1002": "10.10.160.141",
"8700_ipif_1002": "10.10.160.142"

"5142_2_IpIf1006": "10.10.160.181",
"5170_ipif_1006": "10.10.160.182"

"8700_ipif_1003": "10.10.160.169",
"5170_ipif_1003": "10.10.160.170"

"8700_ipif_1004": "10.10.160.173",
"5170_ipif_1004": "10.10.160.174"

提前致谢

标签: pythonlistdictionary

解决方案


使用itertools.combinations

import itertools

for element in data["neighbors"]:
    for h1, h2 in itertools.combinations(hostnames, 2):
        if h1 in str(element.keys()) and h2 in str(element.keys()):
            print('{} - {}'.format(element.keys(), element.values()))

输出:

dict_keys(['5142_2_IpIf1002', '8700_ipif_1002']) - dict_values(['10.10.160.141', '10.10.160.142'])
dict_keys(['5142_2_IpIf1006', '5170_ipif_1006']) - dict_values(['10.10.160.181', '10.10.160.182'])
dict_keys(['8700_ipif_1003', '5170_ipif_1003']) - dict_values(['10.10.160.169', '10.10.160.170'])
dict_keys(['8700_ipif_1004', '5170_ipif_1004']) - dict_values(['10.10.160.173', '10.10.160.174'])

推荐阅读