![](/img/trans.png)
[英]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.