I got a large list of JSON objects that I want to parse depending on the start of one of the keys, and just wildcard the rest. A lot of the keys are similar, like "matchme-foo" and "matchme-bar". There is a builtin wildcard, but it is only used for whole values, kinda like an else.

I might be overlooking something but I can't find a solution anywhere in the proposal:

https://docs.python.org/3/whatsnew/3.10.html#pep-634-structural-pattern-matching

Also a bit more about it in PEP-636:

https://www.python.org/dev/peps/pep-0636/#going-to-the-cloud-mappings

My data looks like this:

data = [{
          "id"     : "matchme-foo",
          "message": "hallo this is a message",
      },{
          "id"     : "matchme-bar",
          "message": "goodbye",
      },{
          "id"     : "anotherid",
          "message": "completely diffrent event"
      }, ...]

I want to do something that can match the id without having to make a long list of |'s.

Something like this:

for event in data:
    match event:
        case {'id':'matchme-*'}: # Match all 'matchme-' no matter what comes next
            log.INFO(event['message'])
        case {'id':'anotherid'}:
            log.ERROR(event['message'])

It's a relatively new addition to Python so there aren't many guides on how to use it yet.

推荐答案

You can use a guard:

for event in data:
    match event:
        case {'id': x} if x.startswith("matchme"): # guard
            print(event["message"])
        case {'id':'anotherid'}:
            print(event["message"])

Quoting from the official documentation,

Guard

We can add an if clause to a pattern, known as a “guard”. If the guard is false, match goes on to try the next case block. Note that value capture happens before the guard is evaluated:

match point:
     case Point(x, y) if x == y:
         print(f"The point is located on the diagonal Y=X at {x}.")
     case Point(x, y):
         print(f"Point is not on the diagonal.")

See also:

Python-3.x相关问答推荐

根据其他数据框架的列顺序从数据框架中进行 Select

使用魔方无法从图像中识别单个字符

我的SELECT函数搜索的是列,而不是列中的数据.我怎么才能让它搜索数据呢?

Numpy argmin()以查找最近的元组

使用 Python 在特定组的列中设置上限

删除给定数组中所有元素为True的所有子数组

Pandas 按值和索引对 DF 进行排序

Python多进程:运行一个类的多个实例,将所有子进程保留在内存中

使用 from re findall 组合连续匹配并分离非连续匹配

如何在 django 中没有循环的情况下获得前键的前键?

类型提示和链式赋值以及多重赋值

合并两个numpy数组

如何从字典中打印特定键值?

Python - For 循环数百万行

理解 Keras 的 ImageDataGenerator 类中的 `width_shift_range` 和 `height_shift_range` 参数

如何在 Python 中计算 cohen 的 d?

清除 PyCharm 运行窗口

有没有一种标准方法来确保 python 脚本将由 python2 而不是 python3 解释?

字典理解中的操作顺序

Python:如何在 Windows 资源管理器中打开文件夹(Python 3.6.2、Windows 10)