Get Nested Value | Challenge

PythonPythonBeginner
Practice Now

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

Introduction

In Python, dictionaries and lists can contain nested values, which can be accessed using a list of selectors. In this challenge, you will create a function that retrieves the value of the nested key indicated by the given selector list from a dictionary or list.


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-13116{{"`Get Nested Value | Challenge`"}} python/lists -.-> lab-13116{{"`Get Nested Value | Challenge`"}} python/tuples -.-> lab-13116{{"`Get Nested Value | Challenge`"}} python/dictionaries -.-> lab-13116{{"`Get Nested Value | Challenge`"}} python/function_definition -.-> lab-13116{{"`Get Nested Value | Challenge`"}} python/importing_modules -.-> lab-13116{{"`Get Nested Value | Challenge`"}} python/using_packages -.-> lab-13116{{"`Get Nested Value | Challenge`"}} python/standard_libraries -.-> lab-13116{{"`Get Nested Value | Challenge`"}} end

Get Nested Value

Problem

Write a function get(d, selectors) that takes a dictionary or list d and a list of selectors selectors as arguments and returns the value of the nested key indicated by the given selector list. If the key does not exist, return None.

To implement this function, use functools.reduce() to iterate over the selectors list. Apply operator.getitem() for each key in selectors, retrieving the value to be used as the iteratee for the next iteration.

Example

users = {
  'freddy': {
    'name': {
      'first': 'fred',
      'last': 'smith'
    },
    'postIds': [1, 2, 3]
  }
}
get(users, ['freddy', 'name', 'last']) ## 'smith'
get(users, ['freddy', 'postIds', 1]) ## 2
get(users, ['freddy', 'age']) ## None

Summary

In this challenge, you learned how to retrieve the value of a nested key from a dictionary or list using a list of selectors. You used functools.reduce() and operator.getitem() to implement the get() function.

Other Python Tutorials you may like