问题描述
"fwt-master2": {
"ipv4": {
"rtr": {
"ip": "1.2.3.4",
"net": "3.4.5.6",
"netlen": "24",
"netmask": "255.255.255.0",
"broadcast": "7.8.9.1"
}
}
我试图从这个 JSON 文件中获取ip
值而不指定每个元素的值(不使用fwt-maser2[ipv4][rtr][ip]
)。
使用.values()
方法(
.values()[0].values()[0].values()[0]`)
我得到的是netlen
值( 24
)而不是实际上是第一个元素的ip
值。
为什么会发生这样的事情?
1楼
我认为使用嵌套代码来查找键值是最好的方法......这样你只需在 dict 中搜索“广播”键然后打印它的值在这里尝试一些东西:
2楼
如果您只知道目标键是"ip"
,那么您可以使用递归:
s = {"fwt-master2": {
"ipv4": {
"rtr": {
"ip": "1.2.3.4",
"net": "3.4.5.6",
"netlen": "24",
"netmask": "255.255.255.0",
"broadcast": "7.8.9.1"
}
}
}
}
def get_ip(d):
return [i for c in filter(None, [b if a == 'ip' else get_ip(b) if isinstance(b, dict) else None for a, b in d.items()]) for i in c]
print(''.join(get_ip(s)))
输出:
1.2.3.4
3楼
我决定翻阅你的字典,发现它不完整!!!
你的字典:
"fwt-master2": {
"ipv4": {
"rtr": {
"ip": "1.2.3.4",
"net": "3.4.5.6",
"netlen": "24",
"netmask": "255.255.255.0",
"broadcast": "7.8.9.1"
}
}
实际上它应该是这样的:添加了缺少的花括号......第一个和最后两个..
{"fwt-master2": { "ipv4": { "rtr": { "ip": "1.2.3.4", "net": "3.4.5.6", "netlen": "24", "netmask": "255.255.255.0", "broadcast": "7.8.9.1" }}}}
嗯,它发生了......所以上面更新的有趣的是实际的字典所以这里是你如何实现你的目标:
>>> d = {"fwt-master2": { "ipv4": { "rtr": { "ip": "1.2.3.4", "net": "3.4.5.6", "netlen": "24", "netmask": "255.255.255.0", "broadcast": "7.8.9.1" }}}}
>>> obj = []
>>> obj.append(d)
>>> obj
[{'fwt-master2': {'ipv4': {'rtr': {'net': '3.4.5.6', 'netlen': '24', 'ip': '1.2.3.4', 'netmask': '255.255.255.0', 'broadcast': '7.8.9.1'}}}}]
>>> key_list = ['netmask', 'broadcast', 'ip', 'net']
>>> def recursive_items(dictionary):
... for key, value in dictionary.items():
... if type(value) is dict:
... yield from recursive_items(value)
... else:
... yield (key, value)
...
>>> def find_key(obj):
... for e in obj:
... for key, value in recursive_items(e):
... if key in key_list:
... print(key, value)
... for key, value in recursive_items(e):
... if key in key_list and value == 0:
... print(double_quote(key),":", value)
...
>>> find_key(obj)
net 3.4.5.6
ip 1.2.3.4
netmask 255.255.255.0
broadcast 7.8.9.1
玩得开心