Pluck values from list of dictionaries

OSCC · Python, List, Dictionary · Oct 22, 2020

Converts a list of dictionaries into a list of values corresponding to the specified key.

  • Use a list comprehension and dict.get() to get the value of key for each dictionary in lst.
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]

Recommended snippets

  • Combines two lists into a dictionary, using the first one as the keys and the second one as the values.

  • Maps the values of a list to a dictionary using a function.

  • Value frequencies

    Python, List

    Creates a dictionary with the unique values of a list as keys and their frequencies as the values.