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

yipeiwu_com5年前Python基础

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

话不多说,直接上代码:

 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

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设计】。

相关文章

学Python 3的理由和必要性

Python很多年前就已经出现了,并且还在不断发展。本书第1版基 于Python 1.5.2,Python 2.x作为主流版本已经持续了很多年。本书是基 于Python 3.6的,并在P...

python实现Adapter模式实例代码

python实现Adapter模式实例代码

本文研究的主要是python实现Adapter模式的相关内容,具体实现代码如下。 Adapter模式有两种实现方式一种是类方式。 #理解 #就是电源适配器的原理吧,将本来不兼容的接...

python实现WebSocket服务端过程解析

python实现WebSocket服务端过程解析

一种类似Flask开发的WebSocket-Server服务端框架,适用python3.X 1、安装模块Pywss pip install pywss 2、搭建简易服务器 2....

python可视化实现代码

python可视化实现代码

python可视化 #导入两个库 import numpy as np import matplotlib.pyplot as plt #第一个参数就是x轴的初始值 #第二个参数是...

Python Datetime模块和Calendar模块用法实例分析

本文实例讲述了Python Datetime模块和Calendar模块用法。分享给大家供大家参考,具体如下: datetime模块 1.1 概述 datetime比time高级了不少,可...