简体   繁体   中英

How to get values from dictionary in python?

I want to add value of entity_id with attribute for type which is String . Below are the details of code:

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': 'Room3',
             'temperature': {'value': '10', 'type': 'Number'},
             'pressure':    {'value': '12', 'type': 'Number'}, 
             'type': 'Array',
             'time_index': '2020-08-24T06:23:37.346664'}]

attr = ['temperature','pressure']

self.logger.warning(msg.format( attr, entity_id)

How can i add value of id where type is String with warning msg.format in above code.. New to python so any help on it will be great.Thanks

To get the value of a dictionary key you do the following.

dict = {'a':1, 'b':2}
print(dict['a'])

This will print the result 1

If you have a dictionary inside a dictionary then do the following

dict = {1: {'a': 'abc', 'b': 'xyz'}}
print(dict[1][a])

This will print abc

Another alternative to putting dictionaries inside dictionaries would be to make a particular key hold a tuple, look at the following example

dict = {'a': ('abc', 'xyz'), 'b':('qwe', 12)}

for i in dict:
    print(dict[i][1])

This will iterate through your dictionary and print xyz and 12. You could also give a condition to print it only if it meets a particular age by following this.

You can also iterate through your nested dictionaries if you desire that.

Depending on your need you can make it hold a dictionary or a tuple however, I think a tuple makes it easier to read and understand code (this is my preference).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM