python - 在 Python 中获取下一对字典
问题描述
我有一个字典列表,其中包含我想提取的值。这是列表的地位。
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
任何人都可以帮忙吗?
解决方案
使用简单的迭代
前任:
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
推荐阅读
- spring-boot - Docker容器内的Log4j2套接字附加程序抛出连接被拒绝
- javascript - 按数组过滤对象并按此数组查看 Viewjs
- typescript - TypeScript 泛型错误(使用 `Partial
`对于`?超级T`) - javascript - Axios-React 原生 PUT 请求
- c# - .net 5 Web API - 使用身份和 Microsoft AD 进行身份验证
- python - 是否有用于评估简单表达式的模块?
- c++ - 每次调试后我每次都会遇到这个错误,这是我正在使用的 g++ 编译器
- opencart - 在 OpenCart 版本 3.0.3.7 中更改类别 url
- excel - 在 Excel 中排列数据
- git - 如何编写用于在 AWS 中构建项目的管道脚本?