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

2024-09-30 16:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经实现了使用CLI客户端访问DB的代码

我可以根据需要得到值

考虑以下代码:

# 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',如果有,我需要得到相同的服务\u id

有人让我知道我们怎样才能达到同样的目标

使用的库:https://github.com/openstack/python-cloudkittyclient


Tags: 代码nameclientidgetserviceconnkwargs
2条回答

查看库中的一些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']
 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_)

注意,根据上面的打印,我假设类的行为类似于字典

相关问题 更多 >