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

相关文章

Python2.6版本中实现字典推导 PEP 274(Dict Comprehensions)

之前自己也遇到过一次,这段时间在群里也遇到过几次的一个问题 用python2.7写的一段程序,里面用到了字典推导式,但是服务器版本是python2.6,无法运行。 今天查了下关于Dict...

python中执行shell的两种方法总结

一、使用python内置commands模块执行shell commands对Python的os.popen()进行了封装,使用SHELL命令字符串作为其参数,返回命令的结果数据以及命令...

python求众数问题实例

本文实例讲述了python求众数问题的方法,是一个比较典型的应用。分享给大家供大家参考。具体如下: 问题描述: 多重集中重数最大的元素称为众数...就是一个可以有重复元素的集合,在这个集...

用pyqt5 给按钮设置图标和css样式的方法

如下所示: 设置图标 self.pushButton.setIcon(QIcon("sure.png")) 设置css样式 self.pushButton.setStyleSh...

python中pygame模块用法实例

python中pygame模块用法实例

本文实例讲述了python中pygame模块用法,分享给大家供大家参考。具体方法如下: import pygame, sys from pygame.locals import *...