首页 > 解决方案 > 在 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

任何人都可以帮忙吗?

标签: pythondictionary

解决方案


使用简单的迭代

前任:

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

推荐阅读