"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']
我想知道是否有办法使用模式匹配来解决这个问题,只是出于好奇。