简体   繁体   中英

How do i fetch first key value pair (i.e., 'type': 45) from a dictionary which contains key as list with dictionaries

{'alarms': [{'date': '20170925T235525-0700',
             'id': 8,
             'ip': '172.26.70.4',
             'severity': 4,
             'type': 45},
            {'date': '20170925T235525-0700',
             'id': 7,
             'ip': '172.26.70.4',
             'severity': 4,
             'type': 45},
            {'date': '20170925T235525-0700',
             'id': 6,
             'ip': '172.26.70.4',
             'severity': 4,
             'type': 45},
            {'date': '20170925T220858-0700',
             'id': 5,
             'ip': '172.26.70.4',
             'severity': 6,
             'type': 44},
            {'date': '20170925T220857-0700',
             'id': 4,
             'ip': '172.26.70.4',
             'severity': 6,
             'type': 44},
            {'date': '20170925T220857-0700',
             'id': 3,
             'ip': '172.26.70.4',
             'severity': 6,
             'type': 44},
            {'date': '20170925T220856-0700',
             'id': 2,
             'severity': 6,
             'type': 32},
            {'date': '20170925T220850-0700', 'id': 1, 'severity': 6, 'type': 1},
            {'date': '20170925T220850-0700',
             'id': 0,
             'severity': 6,
             'type': 33}]}

Need to fetch first key value pair (ie, 'type': 45)

Kindly guide, I am trying it on Python 2.7.

Your data is a dictionary where the `"alarms" key is associated with a list of dictionaries.

That dictionary is in the list associated with the "alarms" key. So you can fetch it with:

data['alarms'][0]

with data the variable that stores this structure. So:

>>> data['alarms'][0]
{'date': '20170925T235525-0700', 'severity': 4, 'id': 8, 'ip': '172.26.70.4', 'type': 45}

you will need to do :

def return_correct_dict(data):
    for d in data['alarms']:
        if d.get('type',"") == 45:
            return d

You have a dictionary of a list of dictionaries. Suppose your dictionary is stored in a variable named dict .

dict['alarm'][0]['type'] will give you the value 45.

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