Get Nested Value

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

Get Nested Value

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.

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

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