python - 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"
提前致谢
解决方案
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'])
推荐阅读
- java - .noSuchElementException 询问用户输入时
- algorithm - 在每个语句的末尾给出次数。对于循环头的情况,只需给出将被检查的次数
- vue.js - 如何多次添加vue.js组件@click?
- css - 为什么高像素密度的小屏幕会呈现错误的媒体查询?
- reactjs - 打字稿,样式组件错误:TS2769:没有重载匹配此调用。重载 1 of 2
- django - Docker-compose:使用 Bolt 从 Web 容器到 Neo4j 容器的 db 连接
- c# - Set-Cookie 中的 Cookie 被浏览器忽略
- jenkins - Jenkins 启动失败 - 验证您是否有足够的权限来启动系统服务
- r - 如何创建堆叠和分组图表?
- elm - 如何在 elm 中为 http get 请求编写测试