因一些特殊需求需要以参数的形式获取字典中特定的值,网上搜了一下并没有特别好的实现 (并没有太认真去找~),所以自己实现了一个,以供大家参考:) 。
话不多说,直接上代码:
def dict_get(dic, locators, default=None):
'''
:param dic: 输入需要在其中取值的原始字典 <dict>
:param locators: 输入取值定位器, 如:['result', 'msg', '-1', 'status'] <list>
:param default: 进行取值中报错时所返回的默认值 (default: None)
:return: 返回根据参数locators找出的值
'''
if not isinstance(dic, dict) or not isinstance(locators, list):
return default
value = None
for locator in locators:
if not type(value) in [dict, list] and isinstance(locator, str) and not can_convert_to_int(locator):
try:
value = dic[locator]
except KeyError:
return default
continue
if isinstance(value, dict):
try:
value = dict_get(value, [locator])
except KeyError:
return default
continue
if isinstance(value, list) and can_convert_to_int(locator):
try:
value = value[int(locator)]
except IndexError:
return default
continue
return value
def can_convert_to_int(input):
try:
int(input)
return True
except BaseException:
return False
好的我们来进行一次简单的最佳实践:)
if __name__ == '__main__':
dict_test = {"result": {"code": "110002", "msg": [{'status': 'ok'}, {'status': 'failed'}]}}
result = dict_get(dict_test, ['result', 'msg', '-1', 'status'])
print(result)
下面是控制台的输出,大家可以看到输出是符合预期结果的:)
failed
Process finished with exit code 0
这次分享到此为止~ 我们有缘再见:)