Skip to content Skip to sidebar Skip to footer

Python How To Get Value From List For Specific Type

I want to print value of entity_id and attribute for type which is String e.g, entities = [{'id': 'Room1', 'temperature': {'value': '10', 'type': 'String'},

Solution 1:

You can check if an attribute itself is a dict using isinstance(obj, type) - if it is you need to "descend" into it. You could flatten your dicts like so:

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/Booleanid = 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 itifisinstance(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 contentprint(f"id: {id} - attribute {key} = {ent[key]}")
    print()

Output:

id:Room1-attributetemperaturehasavalueof10id:Room1-attributepressurehasavalueof12id:Room1-attributetype=Roomid:Room1-attributetime_index=2020-08-24T06:23:37.346348id:Room2-attributetemperaturehasavalueof10id:Room2-attributepressurehasavalueof12id:Room2-attributetype=Roomid:Room2-attributetime_index=2020-08-24T06:23:37.346664

Solution 2:

You were on the right track with looping over the list but you need to loop into each Dictionary to look for your type.

To iterate over the key value pairs of each :

for key, value in e.items():

Then to check your types of nested Dictionaries you first type check it, make sure the key exists, and finally make sure it's not of type NSGI_TYPE. All together this looks like:

for e in entities:
    entity_id = ""# put entity_id into scope for our loopfor key, value in e.items():
    # loop over the { ... }if key == "id":
            entity_id = str(value)
        # keep track of id to output lateriftype(value) isdict:
            if"type"in value.keys():
            # if type isn't in the { ... } there's no point in continuingif value["type"] != NSGI_TYPE:
                    print(entity_id)
                    print(key, value)
                else:
                    msg = "Entity {} is type {}."raise ValueError(msg.format(e[NGSI_ID], entity_type))

Post a Comment for "Python How To Get Value From List For Specific Type"