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

yipeiwu_com6年前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 使用while写猜年龄小游戏过程解析

需求: 用户一轮有三次机会进行猜年龄游戏,每猜一次会给相应的提示告知用户应该往大点猜或者小点猜,三次机会用完以后,可选择重新再来三次机会。 思路: 首先定义一个初始年龄为25和初始次数0...

通过实例学习Python Excel操作

通过实例学习Python Excel操作

这篇文章主要介绍了通过实例学习Python Excel操作,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.python 读取Exc...

python实现公司年会抽奖程序

本文实例为大家分享了python实现年会抽奖程序的具体代码,供大家参考,具体内容如下 发一下自己写的公司抽奖程序。 需求:公司年会要一个抽奖程序,转盘上的每一个人名是随机中奖的,中奖后的...

python查询mysql中文乱码问题

问题: python2.7 查询或者插入中文数据在mysql中的时候出现中文乱码 --- 可能情况: 1.mysql数据库各项没有设置编码,默认为'latin' 2.使用MySQL.co...

nohup后台启动Python脚本,log不刷新的解决方法

问题: =》nohup python3 xxxx.py &后台启动脚本 tail -100f nohup.out    -------->  &nbs...