tgcloud
tgcloud

Reputation: 887

Unable to fetch key from nested dict

I got below output from 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'
}

I am writing python script to get the compute node details in the Availability Zone.

I am able to get the host name, however i am trying to fetch hosts status "u'available": True, and "u'active": True,, but i and not able to get the keys form dict.

any help would be appreciated.

Upvotes: 0

Views: 48

Answers (2)

Vaibhav
Vaibhav

Reputation: 325

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

Upvotes: 0

ddor254
ddor254

Reputation: 1628

try this:

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

this will print your desired value

Upvotes: 1

Related Questions