How to create a dictionary with list comprehension with Python?

Sometimes, we want to create a dictionary with list comprehension with Python.

In this article, we’ll look at how to create a dictionary with list comprehension with Python.

How to create a dictionary with list comprehension with Python?

To create a dictionary with list comprehension with Python, we can use the dictionary comprehension syntax in the following format:

{key: value for (key, value) in iterable}

For instance, we write:

ts = [(1, 2), (3, 4), (5, 6)]
d = {key: value for (key, value) in ts}
print(d)

We have the ts array with tuples as elements.

Then we destructure the tuples with for (key, value) in ts and put them into the dictionary as entries.

And then we assign the dictionary to d.

Therefore, d is {1: 2, 3: 4, 5: 6}.

Conclusion

To create a dictionary with list comprehension with Python, we can use the dictionary comprehension syntax in the following format:

{key: value for (key, value) in iterable}