0

"msg"我有以下字典,如果"status"是,我想获取 的值"progress"。状态"progress"或键"msg"可能在字典中,也可能不在字典中,这就是为什么我想到使用模式匹配来查看是否能得到我想要的。

我的尝试

my_dict = {
    "outer": [
        {"status": "to do", "desc": [{"msg": "foo"}]},
        {"status": "progress", "desc": [{"msg": "bar"}]},
        {"status": "done", "desc": [{"msg": "baz"}]},
    ]
}

match my_dict:
    case {'outer': [{'status': 'progress', 'desc': [{'msg': x}]}]}:
        print(x)

我正在寻找类似的东西,case {'outer': [*_, {'status': 'progress', 'desc': [{'msg': x}]}, *_]}:但这不起作用SyntaxError: multiple starred names in sequence pattern

我想要的输出(使用模式匹配)

bar

我可以通过以下方式获得我想要的东西,但是我需要做一些检查以确保密钥存在。

for i in my_dict['outer']: # check every status
    if i['status'] == 'progress': # check if the status is "progress"
        if 'desc' in i:
            for j in i['desc']: # loop the values of "desc"
                if 'msg' in j: # if the msg is there get the value
                    x = j['msg']

我想知道是否有办法使用模式匹配来解决这个问题,只是出于好奇。

4

2 回答 2

1

如果保证该值progress只会在 中出现一次my_dict['outer'],那么您可以在匹配之前预先过滤项目列表:

my_dict = {'outer': [{'status': 'to do', 'desc': [{'msg': 'foo'}]}, {'status': 'progress', 'desc': [{'msg': 'bar'}]}, {'status': 'done', 'desc': [{'msg': 'baz'}]}]}
match [i for i in my_dict['outer'] if i['status'] == 'progress']:
   case [{'status': _, 'desc': [{'msg': msg}]}]:
      print(msg)

输出:

'bar'
于 2021-11-24T15:02:21.337 回答
1

我想您可以执行以下操作:

for info in my_dict["outer"]:
    match info:
        case {"status": "progress", "desc": [{"msg": msg}]}:
            print(msg)
            break
else:
    print("No Match")
于 2021-11-24T08:09:01.450 回答