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读取word 中指定位置的表格及表格数据

python读取word 中指定位置的表格及表格数据

1.Word文档如下: 2.代码 # -*- coding: UTF-8 -*- from docx import Document def readSpecTable(filen...

pytorch 实现模型不同层设置不同的学习率方式

在目标检测的模型训练中, 我们通常都会有一个特征提取网络backbone, 例如YOLO使用的darknet SSD使用的VGG-16。 为了达到比较好的训练效果, 往往会加载预训练的b...

Python坐标线性插值应用实现

Python坐标线性插值应用实现

一、背景 在野外布设700米的测线,点距为10米,用GPS每隔50米测量一个坐标,再把测线的头和为测量一个坐标。现在需使用线性插值的方法求取每两个坐标之间的其他4个点的值。 二、插值原...

用python实现的线程池实例代码

python3标准库里自带线程池ThreadPoolExecutor和进程池ProcessPoolExecutor。 如果你用的是python2,那可以下载一个模块,叫threadpoo...

python使用xmlrpclib模块实现对百度google的ping功能

本文实例讲述了python使用xmlrpclib模块实现对百度google的ping功能。分享给大家供大家参考。具体分析如下: 最近在做SEO的时候,为了让发的外链能够快速的收录,想到了...