Python如何从特定类型的列表中获取值

2024-09-29 17:21:13 发布

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

我想打印类型为Stringentity_idattribute的值,例如

entities = [{'id': 'Room1',
             'temperature': {'value': '10', 'type': 'String'}, 
             'pressure':    {'value': '12', 'type': 'Number'}, 
             'type': 'Room',
             'time_index': '2020-08-24T06:23:37.346348'}, 

            {'id': 'Room2',
             'temperature': {'value': '10', 'type': 'Number'},
             'pressure':    {'value': '12', 'type': 'Number'}, 
             'type': 'Room',
             'time_index': '2020-08-24T06:23:37.346664'}]

ngsi_type = ( 'Array', 'Boolean')
    

这是代码的实际定义,我想在其中打印id and attribute的值,即temperature , pressure对于type它不是ngsi_type,例如,对于type : String,我想打印它的entity_id and attribute的值

 def _insert_entities_of_type(self,
                              entity_type,
                              entities,
                              fiware_service=None,
                              fiware_servicepath=None):
    for e in entities:
        if e[NGSI_TYPE] != entity_type:
            msg = "Entity {} is not of type {}."
            raise ValueError(msg.format(e[NGSI_ID], entity_type))

关于它的任何帮助,因为我是python新手,不能用msg打印除ngsi类型之外的id and attribute:temperature , pressure


Tags: andid类型numberstringvaluetypeattribute
2条回答

您可以使用isinstance(obj, type)检查属性本身是否是dict-如果是,您需要“下降”到其中。你可以这样压扁你的口述:

entities = [{'id': 'Room1',
             'temperature': {'value': '10', 'type': 'String'}, 
             'pressure':    {'value': '12', 'type': 'Number'}, 
             'type': 'Room',
             'time_index': '2020-08-24T06:23:37.346348'}, 

            {'id': 'Room2',
             'temperature': {'value': '10', 'type': 'Number'},
             'pressure':    {'value': '12', 'type': 'Number'}, 
             'type': 'Room',
             'time_index': '2020-08-24T06:23:37.346664'},

            {'id': 'Room not shown due to type',
             'temperature': {'value': '10', 'type': 'Number'},
             'pressure':    {'value': '12', 'type': 'Number'}, 
             'type': 'Array',
             'time_index': '2020-08-24T06:23:37.346664'}]

ngsi_type = ('Array', 'Boolean')

for ent in entities:
    if ent["type"] in ngsi_type:
        continue   # do not show any entities that are of type Array/Boolean
    id = ent["id"]
    for key in ent:  # check each key of the inner dict 
        if key == "id":
            continue # do not print the id

        # if dict, extract the value and print a message, else just print it
        if isinstance(ent[key], dict):
            print(f"id: {id} - attribute {key} has a value of {ent[key]['value']}")
        else:
            # remove if only interested in attribute/inner dict content
            print(f"id: {id} - attribute {key} = {ent[key]}")
    print()

输出:

id: Room1 - attribute temperature has a value of 10
id: Room1 - attribute pressure has a value of 12
id: Room1 - attribute type = Room
id: Room1 - attribute time_index = 2020-08-24T06:23:37.346348

id: Room2 - attribute temperature has a value of 10
id: Room2 - attribute pressure has a value of 12
id: Room2 - attribute type = Room
id: Room2 - attribute time_index = 2020-08-24T06:23:37.346664

您在列表上的循环是正确的,但是您需要循环到每个字典中查找您的类型

要迭代每个的键值对,请执行以下操作:

for key, value in e.items():

然后要检查嵌套字典的类型,首先要键入check,确保键存在,最后确保它不是NSGI_类型。所有这些看起来像:

for e in entities:
    entity_id = ""
    # put entity_id into scope for our loop

    for key, value in e.items():
    # loop over the { ... }

        if key == "id":
            entity_id = str(value)
        # keep track of id to output later

        if type(value) is dict:
            if "type" in value.keys():
            # if type isn't in the { ... } there's no point in continuing
                if value["type"] != NSGI_TYPE:
                    print(entity_id)
                    print(key, value)
                else:
                    msg = "Entity {} is type {}."
                    raise ValueError(msg.format(e[NGSI_ID], entity_type))

相关问题 更多 >

    热门问题