[英]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) 需要获取第一个键值对(即“类型”:45)
Kindly guide, I am trying it on Python 2.7. 谨此指导,我正在Python 2.7上进行尝试。
Your data is a dictionary where the `"alarms" key is associated with a list of dictionaries. 您的数据是一个字典,其中“ alarms”键与一个词典列表相关联。
That dictionary is in the list associated with the "alarms"
key. 该词典在与
"alarms"
键关联的列表中。 So you can fetch it with: 因此,您可以通过以下方式获取它:
data['alarms'][0]
with data
the variable that stores this structure. 与
data
存储该结构的变量。 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的变量中。
dict['alarm'][0]['type'] will give you the value 45.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.