【问题标题】:Unable to fetch key from nested dict无法从嵌套字典中获取密钥
【发布时间】:2018-03-07 15:08:50
【问题描述】:

我从 Openstack nova API 得到以下输出。

{
    "u'zoneState": {
        "u'available": True
    },
    "u'hosts": {
        "u'compute-1": {
            "u'nova-compute": {
                "u'available": True,
                "u'active": True,
                "u'updated_at":
                "u'2017-09-26T10":
                "04": 49.000000'
            }
        },
        "u'compute-2": {
            "u'nova-compute": {
                "u'available": True,
                "u'active": True,
                "u'updated_at":
                "u'2017-09-26T10":
                "04": 48.000000'
            }
        }
    },
    "u'zoneName": u'nova'
}

我正在编写 python 脚本来获取可用区中的计算节点详细信息。

我能够获取主机名,但是我正在尝试获取主机状态 "u'available": True,"u'active": True,,但我无法从字典中获取密钥。

任何帮助将不胜感激。

【问题讨论】:

    标签: python json python-2.7 dictionary nested


    【解决方案1】:

    试试这个:

    for host_key in d["u'hosts"].keys():
        for key in d["u'hosts"][host_key]:
            print d["u'hosts"][host_key][key].get("u'active")
    

    这将打印您想要的值

    【讨论】:

    • 感谢您的回复。但是,它总是抛出 None>>> for host_key in your_dictionary['hosts'].keys(): ... print your_dictionary['hosts'][host_key].get('active') ... None
    【解决方案2】:
    for x in openstack_dict["u'hosts"].iterkeys():
        if len(openstack_dict["u'hosts"][x]) > 0:
            for y in openstack_dict["u'hosts"][x].iterkeys():
                if len(openstack_dict["u'hosts"][x][y]) > 0:
                    for z in openstack_dict["u'hosts"][x][y].iterkeys():
                        print x,':',y,':',z,':', openstack_dict["u'hosts"][x][y][z]
                else:
                    print openstack_dict["u'hosts"][x]
        else:
            print openstack_dict["u'hosts"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2013-02-19
      • 2015-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多