Skip to content

Python list comprehension dictionary

  • by

Using the dict() method you can convert list comprehension to the dictionary in Python. Other methods are zip() with dict() method or Iterable.

dict(list_comprehension)
#OR
dict(zip(key_list,value_list))     
#OR
{key: value for (key, value) in data}

Python list comprehension dictionary

Simple example code Using dict() method.

data = [('A', 23), ('B', 15), ('C', 8), ('D', 4), ('E', 20)]
print(data)
print(type(data))

# using dict method
d = dict(data)
print(d)
print(type(dict(d)))

Output:

Python list comprehension dictionary

Using zip() with dict() method

name = ['A', 'B', 'C', 'D', 'E']

age = [23, 21, 32, 11, 23]

# using dict method with zip()
dict(zip(name, age))

Using Iterable

data = [('A', 23), ('B', 15), ('C', 8), ('D', 4), ('E', 20)]

d = {key: value for (key, value) in data}
print(d)

You can customize the expressions inside the curly braces {} according to your specific requirements for creating the dictionary.

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading