Open In App

Create a Dictionary with List Comprehension in Python

Last Updated : 08 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of creating a dictionary with list comprehension in Python involves iterating through a sequence and generating key-value pairs in a concise manner. For example, given two lists, keys = [“name”, “age”, “city”] and values = [“Alice”, 25, “New York”], we can pair corresponding elements using list comprehension and convert them into a dictionary, resulting in {‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘New York’}.

Using zip()

zip() pairs elements from two lists and is commonly used to create dictionaries efficiently. By wrapping zip() inside a list comprehension and converting it into a dictionary using dict(), we can merge two lists into key-value pairs. It ensures that elements are mapped correctly without extra iterations.

Python
keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]

d = dict([(k, v) for k, v in zip(keys, values)])
print(d)

Output
{'name': 'Alice', 'age': 25, 'city': 'New York'}

Explanation: zip(keys, values) pairs elements into tuples like [(‘name’, ‘Alice’), (‘age’, 25), (‘city’, ‘New York’)]. Then, list comprehension generates a list of key-value pairs, which dict() converts into a dictionary, storing it in d.

Using dict()

Dictionary can be created by passing a list of tuples to the dict(). Using list comprehension, we first generate a list of tuples, where each tuple consists of a key-value pair. This method is useful when keys and values are derived through computations, such as squaring numbers or mapping values dynamically.

Python
a = [(x, x**2) for x in range(1, 6)]
d = dict(a)
print(d)

Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Explanation: List comprehension generates a list of tuples, where each tuple consists of a number x (from 1 to 5) as the first element and its square (x**2) as the second. Then, this list of tuples is converted into a dictionary using dict().

Using enumerate()

enumerate() assigns an index to each element in an iterable, making it useful for generating dictionaries with numeric keys. By applying list comprehension, we can create a list of (index, value) pairs and convert it into a dictionary. It ensures a structured and ordered mapping of elements.

Python
a = ["apple", "banana", "cherry"]

d = dict([(idx, val) for idx, val in enumerate(a)])
print(d)

Output
{0: 'apple', 1: 'banana', 2: 'cherry'}

Explanation: List comprehension iterates over enumerate(a), assigning an index to each element in a, creating tuples (idx, val). These tuples are then passed to dict(), converting them into a dictionary where indexes are keys and list elements are values.



Next Article

Similar Reads