检查类对象的特定值并获取另一个键的值

时间:2016-05-24 04:35:44

标签: python list dictionary openstack

我已经实现了使用CLI客户端访问数据库的代码。

我可以根据需要获取值。

请考虑以下代码:

# Establish the connection Cloudkitty
ck = client.get_client(kwargs_conn.get('cloudkitty_version'), **kwargs_conn)

list_services = ck.hashmap.services.list()

for services in list_services:

        print services
        print(type(services))

它将产生如下输出:

<hashmap.Service {u'service_id': u'2c6e0447-0cdb-4d12-8511-4544ba0d03b5', u'name': u'compute'}>
<class 'cloudkittyclient.v1.rating.hashmap.Service'>
<hashmap.Service {u'service_id': u'48297131-de33-48ad-b5b5-43d3a3177841', u'name': u'volume'}>
<class 'cloudkittyclient.v1.rating.hashmap.Service'>

正在重新调整的输出用作类对象。

现在我需要检查返回的对象以获取密钥的特定值。确切地说,我想检查它是否具有'name'作为'compute',如果是,我需要获得相同的service_id。

有人让我知道我们如何才能实现同样的目标。

使用的图书馆:https://github.com/openstack/python-cloudkittyclient

2 个答案:

答案 0 :(得分:1)

查看库中的部分tests,您似乎可以直接访问service_id等字段:

for service in list_services:
    if service.name == 'compute':
        print(service.service_id)

或者,如果您想获取名称为compute的所有服务的服务ID:

service_ids = [service.service_id for service in list_services if service.name == 'compute']

答案 1 :(得分:0)

 if services.get("name") == "compute":
      id_ = services.get("service_id")

      #assuming li = [] declaration above you could add that to a list 
      # of IDs
      li.append(id_)

注意我从上面的印刷品中假设,该类在行为上类似于字典。