Python create dictionary from list | Example code

There are multiple ways to creates a dictionary from the list in python. A dict comprehension and zip() function are common and simple to create a dictionary from a list.

Must read: Python make dict from list

Example create a dictionary from the list in Python

Simple example code.

Using dictionary comprehension

A dictionary comprehension is similar to a list comprehension in that both methods create a new value of their respective data types.

keys = ["A", "B", "C"]
values = [1, 2, 3]

res = {keys[i]: values[i] for i in range(len(keys))}
print(res)

Output:

Python create dictionary from list

Using zip() Funciton

This is the Most pythonic and generic method to create a dictionary form list. This function pairs the list element with another list element at corresponding index in form of key-value pairs.

keys = ["A", "B", "C"]
values = [1, 2, 3]

res = dict(zip(keys, values))
print(res)

Output: {‘A’: 1, ‘B’: 2, ‘C’: 3}

How do I create a dictionary with keys from a list and default values zero?

Answer: Given key of list a = [1,2,3,4] convert to d = {1:0, 2:0, 3:0, 4:0}

Using dict comprehensions

a = [1, 2, 3, 4]
res = {el: 0 for el in a}

print(res)

Output: {1: 0, 2: 0, 3: 0, 4: 0}

Using dict.fromkeys

a = [1, 2, 3, 4]
res = dict.fromkeys(a, 0)

print(res)

Output: {1: 0, 2: 0, 3: 0, 4: 0}

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

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.