【问题标题】:Retrieve json key on searching child value在搜索子值时检索 json 键
【发布时间】:2017-03-30 23:46:05
【问题描述】:

我有这个 json 对象

{
    '2807281f81481ffbd4183da0003dfe1820343ff6': {
    'macaddr': '64:a3:cb:ba:5c:76',
    'parameters': [
      '1',
      '121',
      '3',
      '6',
      '15',
      '119',
      '252'
    ],
    'ip': '192.168.1.120',
    'vendor_id': 'MSFT 5.0',
    'HOSTID': '2807281f81481ffbd4183da0003dfe1820343ff6',
    'time': 1479309949.7988095,
    'os': 'Apple iPhone',
    'hostname': 'Alles-iPhone'
    }
}

我想要实现的是在搜索特定 ip 时检索密钥。然后使用该键从另一个字典中检索匹配的值。

编辑 1: 我自己回答了。

【问题讨论】:

    标签: json python-2.7 list dictionary


    【解决方案1】:

    我最终使用了列表推导和迭代项。 global_hostlist 是必需的字典,hostlist 是要匹配的字典。

    if ip in [host_ip[1]["ip"] for host_ip in self.global_hostlist.iteritems()]:
        key = [host_ip[1]["HOSTID"] for host_ip in self.global_hostlist.iteritems() if host_ip[1]["ip"] == ip]
        if key[0]:
            self.hostlist[key[0]] = self.global_hostlist[key[0]]
    

    【讨论】:

    • 如果您认为您找到的解决方案对其他用户有帮助,请随时self-answer您的问题。否则,您可以delete your post
    • 我是SO的新手,刚刚意识到。希望它可以帮助某人。我自己回答了。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 2023-02-24
    • 2019-11-11
    • 2022-01-06
    相关资源
    最近更新 更多