【发布时间】:2022-01-02 15:07:56
【问题描述】:
我有以下字典,如果"status" 是"progress",我想获得"msg" 的值。状态"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']
出于好奇,我想知道是否有办法使用模式匹配来解决这个问题。
【问题讨论】:
标签: python pattern-matching python-3.10