Dictionary Comprehension

noun

say it: “DIK-shuh-nair-ee kom-prih-HEN-shun” /ˈdɪkʃəˌnɛri ˌkɑmprɪˈhɛnʃən/

A one-line way to build a new dictionary from another collection, written in curly braces with a key: value expression and a for.

What is a dictionary comprehension?

A dictionary comprehension builds a new dictionary in one line, the same way a list comprehension builds a list.

names = ["ana", "ben"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)  # {'ana': 3, 'ben': 3}

In a sentence

  • “A dictionary comprehension turned the price list into prices with tax.”
  • “The dictionary comprehension {name: len(name) for name in names} maps each name to its length.”

Level: Journeyman · More Python terms at this level

Updated