使用.values()从JSON最后一个键级别错误的值

时间:2018-02-11 14:44:50

标签: python dictionary

"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值。

为什么会发生这样的事情?

3 个答案:

答案 0 :(得分:0)

我认为使用嵌套代码来查找键值是最好的方法...这样你只需搜索dict中的“broadcast”键然后打印它的值 在这里尝试一下rom:find all occurances of a key

答案 1 :(得分:0)

如果您只知道目标键是"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

答案 2 :(得分:-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"
                    }
            }

实际上它应该是这样的:添加缺少花括号......第一个和最后两个..

{"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

玩得开心