python字典嵌套字典的情况下获取某个key的value

1 #coding: utf-8
2 import types
3
4 #获取字典中的objkey对应的值,适用于字典嵌套
5 #dict:字典
6 #objkey:目标key
7 #default:找不到时返回的默认值
8 def dict_get(dict, objkey, default):
9 tmp = dict
10 for k,v in tmp.items():
11 if k == objkey:
12 return v
13 else:
14 if type(v) is types.DictType:
15 ret = dict_get(v, objkey, default)
16 if ret is not default:
17 return ret
18 return default
19
20 #如
21 dicttest={“result”:{“code”:“110002”,“msg”:“设备设备序列号或验证码错误”}}
22 ret=dict_get(dicttest, ‘msg’, None)
23 print(ret)

你可能感兴趣的:(python字典嵌套字典的情况下获取某个key的value)