获取嵌套值

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,字典和列表可以包含嵌套值,这些值可以使用选择器列表来访问。在这个挑战中,你将创建一个函数,该函数从字典或列表中检索由给定选择器列表指示的嵌套键的值。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") subgraph Lab Skills python/comments -.-> lab-13648{{"获取嵌套值"}} python/lists -.-> lab-13648{{"获取嵌套值"}} python/tuples -.-> lab-13648{{"获取嵌套值"}} python/dictionaries -.-> lab-13648{{"获取嵌套值"}} python/function_definition -.-> lab-13648{{"获取嵌套值"}} python/importing_modules -.-> lab-13648{{"获取嵌套值"}} python/using_packages -.-> lab-13648{{"获取嵌套值"}} python/standard_libraries -.-> lab-13648{{"获取嵌套值"}} end

获取嵌套值

编写一个函数 get(d, selectors),它接受一个字典或列表 d 和一个选择器列表 selectors 作为参数,并返回由给定选择器列表指示的嵌套键的值。如果键不存在,则返回 None

要实现此函数,请使用 functools.reduce() 遍历 selectors 列表。对 selectors 中的每个键应用 operator.getitem(),获取要用作下一次迭代的迭代值的值。

from functools import reduce
from operator import getitem

def get(d, selectors):
  return reduce(getitem, selectors, d)
users = {
  'freddy': {
    'name': {
      'first': 'fred',
      'last': 'smith'
    },
    'postIds': [1, 2, 3]
  }
}
get(users, ['freddy', 'name', 'last']) ## 'smith'
get(users, ['freddy', 'postIds', 1]) ## 2

总结

在这个挑战中,你学习了如何使用选择器列表从字典或列表中检索嵌套键的值。你使用了 functools.reduce()operator.getitem() 来实现 get() 函数。