damini chopra
damini chopra

Reputation: 133

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'}, 
             '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')
    

This is the actual definition of code where i want to print value of id and attribute ie, temperature , pressure for type which is not ngsi_type for e.g, for type : String i want value of its entity_id and attribute to be printed

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

Any help on it as i am new to python not able to print value of id and attribute:temperature , pressure other than ngsi type with msg

Upvotes: 0

Views: 631

Answers (2)

Sean Behan
Sean Behan

Reputation: 48

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

Upvotes: 1

Patrick Artner
Patrick Artner

Reputation: 51683

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/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()

Output:

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

Upvotes: 1

Related Questions