• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python使用参数对嵌套字典进行取值的方法

python 搞代码 4年前 (2022-01-08) 22次浏览 已收录 0个评论

这篇文章主要介绍了python使用参数对嵌套字典进行取值,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

因一些特殊需求需要以参数的形式获取字典中特定的值,网上搜了一下并没有特别好的实现(并没有太认真去找~),所以自己实现了一个,以供大家参考:) 。

话不多说,直接上代码:

 def dict_get(dic, locators, default=None): ''' :param dic: 输入需要在其中取值的原始字典  :param locators: 输入取值定位器, 如:['result', 'msg', '-1', 'status']  :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 

Best Practice

好的我们来进行一次简单的最佳实践:)

 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

这次分享到此为止~ 我们有缘再见:)

以上就是python使用参数对嵌套字典进行取值的方法的详细内容,更来源gao*daima.com搞@代#码网多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python使用参数对嵌套字典进行取值的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址