0

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

4
  • This is already in code i just want to add entity_id and attribute value for specific type which is other than ngsi_type with msg.format.Thanks Commented Aug 24, 2020 at 7:16
  • 1
    To check type, python has inbuilt function called isinstance, for exampleisinstance('abc', str), will return true. This will work for user defined class and its instance too. You can use it to check the instance Commented Aug 24, 2020 at 7:35
  • 1
    I see 3 'type' keys er inner data, I see no field 'entity_id' (only 'id') and I do not see any 'attribute' field. Please be more specific what the outputs should be. Neither of your "type" are "Array" or "Boolean" so currently this should print "as is" ? Commented Aug 24, 2020 at 7:40
  • @PatrickArtner, I have updated question... also attribute are temperature , Pressure . Also, if type is String i want it to print id and attribute with respect to its ` type :String` in msg.format.Thanks Commented Aug 24, 2020 at 7:59

2 Answers 2

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/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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.