获取Python中的下一对字典
我有一个字典列表,其中包含我想提取的值。以下是这份名单的规模获取Python中的下一对字典,python,dictionary,Python,Dictionary,我有一个字典列表,其中包含我想提取的值。以下是这份名单的规模 input = [ [ { "field": "@timestamp", "value": "2019-05-07 13: 40: 31.103" }, { "field": "B", "value": 22 }, { "field": "@message", "value": "123 aaa 456 bbb"
input = [
[
{
"field": "@timestamp",
"value": "2019-05-07 13: 40: 31.103"
},
{
"field": "B",
"value": 22
},
{
"field": "@message",
"value": "123 aaa 456 bbb"
}
],
[
{
"field": "@timestamp",
"value": "2019-05-08 13: 40: 31.103"
},
{
"field": "B",
"value": 11
},
{
"field": "@message",
"value": "123 yyy 456 zzz"
}
]
,
...
]
我想迭代列表,并为每次迭代获取@timestamp
和@message
的值。时间戳总是每个列表的第一个元素,消息是第三个元素,但我不想依赖元素的顺序
这是我到目前为止所做的,但我不知道如何得到下一双
for list in input:
for dict in list:
for x, y in dict.items():
if x == 'field' and y == '@timestamp':
print(y)
# Here i want to get the values of the next pair and continue to the next iteration
elif x == 'field' and y == '@message':
print(y)
# Here i want to get the values of the next pair and continue to the next iteration
任何人都可以帮助?使用简单的迭代 Ex:
data = [
[
{
"field": "@timestamp",
"value": "2019-05-07 13: 40: 31.103"
},
{
"field": "B",
"value": 22
},
{
"field": "@message",
"value": "123 aaa 456 bbb"
}
],
[
{
"field": "@timestamp",
"value": "2019-05-08 13: 40: 31.103"
},
{
"field": "B",
"value": 11
},
{
"field": "@message",
"value": "123 yyy 456 zzz"
}
]
]
for elem in data:
for sub_elem in elem:
if sub_elem["field"] in ["@timestamp", "@message"]:
print(sub_elem["value"])
2019-05-07 13: 40: 31.103
123 aaa 456 bbb
2019-05-08 13: 40: 31.103
123 yyy 456 zzz
输出:
data = [
[
{
"field": "@timestamp",
"value": "2019-05-07 13: 40: 31.103"
},
{
"field": "B",
"value": 22
},
{
"field": "@message",
"value": "123 aaa 456 bbb"
}
],
[
{
"field": "@timestamp",
"value": "2019-05-08 13: 40: 31.103"
},
{
"field": "B",
"value": 11
},
{
"field": "@message",
"value": "123 yyy 456 zzz"
}
]
]
for elem in data:
for sub_elem in elem:
if sub_elem["field"] in ["@timestamp", "@message"]:
print(sub_elem["value"])
2019-05-07 13: 40: 31.103
123 aaa 456 bbb
2019-05-08 13: 40: 31.103
123 yyy 456 zzz
可以向列表中添加枚举数,对循环中的当前索引进行计数。然后以该值提取字典
for list in input:
for i, dict in enumerate(list):
for x, y in dict.items():
if x == 'field' and (y == '@timestamp' or y == '@message'):
print(list[i])
印刷品:
{'field': '@timestamp', 'value': '2019-05-07 13: 40: 31.103'}
{'field': '@message', 'value': '123 aaa 456 bbb'}
{'field': '@timestamp', 'value': '2019-05-08 13: 40: 31.103'}
{'field': '@message', 'value': '123 yyy 456 zzz'}
这对于常规字典来说是个坏主意,键没有排序没有正确的“下一个”如果你坚持这样做,把你的dict变成不确定你所说的“下一对”是什么意思,你能详细说明一下吗?你应该避免将变量命名为与构建时相同的名称-ins@Faboor,下一对
“字段”:“@timestamp”
例如将是“值”:“2019-05-07 13:40:31.103”
。我希望足够清楚。太好了!比我想象的容易多了。谢谢:)