[英]How to access the dictionary from a list of dictionaries using one key/value pair of the dictionary that I want to fetch
[英]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}]}
需要獲取第一個鍵值對(即“類型”:45)
謹此指導,我正在Python 2.7上進行嘗試。
您的數據是一個字典,其中“ alarms”鍵與一個詞典列表相關聯。
該詞典在與"alarms"
鍵關聯的列表中。 因此,您可以通過以下方式獲取它:
data['alarms'][0]
與data
存儲該結構的變量。 所以:
>>> data['alarms'][0]
{'date': '20170925T235525-0700', 'severity': 4, 'id': 8, 'ip': '172.26.70.4', 'type': 45}
您將需要執行以下操作:
def return_correct_dict(data):
for d in data['alarms']:
if d.get('type',"") == 45:
return d
您有詞典列表的字典。 假設您的字典存儲在名為dict的變量中。
dict['alarm'][0]['type'] will give you the value 45.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.