Map list to dictionary

Python, List, Dictionary · Nov 2, 2020

Maps the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value.

  • Use map() to apply fn to each value of the list.
  • Use zip() to pair original values to the values produced by fn.
  • Use dict() to return an appropriate dictionary.
def map_dictionary(itr, fn):
  return dict(zip(itr, map(fn, itr)))
map_dictionary([1, 2, 3], lambda x: x * x) # { 1: 1, 2: 4, 3: 9 }

More like this

  • Python Dictionaries

    A snippet collection of dictionary helpers and tips for Python 3.6.

    Collection · 24 snippets

  • Lists to dictionary

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

    Python, List · Nov 2, 2020

  • What are named tuples in Python?

    Understand Python's named tuples and start using them in your projects today.

    Python, List · Jun 12, 2021

  • Pluck values from list of dictionaries

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

    Python, List · Oct 22, 2020