Pluck values from list of dictionaries

PythonPythonBeginner
Practice Now

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

Introduction

In Python, a dictionary is a collection of key-value pairs. Sometimes, we need to extract specific values from a list of dictionaries. In this challenge, you need to write a function that takes a list of dictionaries and a key as input and returns a list of values corresponding to the specified key.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/ControlFlowGroup -.-> python/list_comprehensions("List Comprehensions") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/function_definition("Function Definition") subgraph Lab Skills python/comments -.-> lab-13705{{"Pluck values from list of dictionaries"}} python/for_loops -.-> lab-13705{{"Pluck values from list of dictionaries"}} python/list_comprehensions -.-> lab-13705{{"Pluck values from list of dictionaries"}} python/lists -.-> lab-13705{{"Pluck values from list of dictionaries"}} python/tuples -.-> lab-13705{{"Pluck values from list of dictionaries"}} python/dictionaries -.-> lab-13705{{"Pluck values from list of dictionaries"}} python/function_definition -.-> lab-13705{{"Pluck values from list of dictionaries"}} end

Pluck values from list of dictionaries

Write a function pluck(lst, key) that takes a list of dictionaries lst and a key key as arguments and returns a list of values corresponding to the specified key.

You need to:

  • Use a list comprehension and dict.get() to get the value of key for each dictionary in lst.
  • The function should return an empty list if the input list is empty or if the specified key is not present in any of the dictionaries.
def pluck(lst, key):
  return [x.get(key) for x in lst]
simpsons = [
  { 'name': 'lisa', 'age': 8 },
  { 'name': 'homer', 'age': 36 },
  { 'name': 'marge', 'age': 34 },
  { 'name': 'bart', 'age': 10 }
]
pluck(simpsons, 'age') ## [8, 36, 34, 10]

Summary

In this challenge, you learned how to extract specific values from a list of dictionaries using a list comprehension and dict.get(). You also learned how to handle empty input lists and non-existent keys.