Python convert list to dictionary keys | Example code

Using Dictionary Comprehension or zip() function will convert list to dictionary keys in Python. If you have 2 lists then one list value will be a key and another one is used as the value.

A single list can be used to convert a key for a dictionary but you have to assign some value for them.

Python convert list to dictionary keys example

Simple example code converting the list into the dictionary. where List stores the heterogeneous data type and Dictionary stores data in key-value pair.

Using Dictionary Comprehension

0 assign as value for every key because the dictionary data is in key-value pair where each key is associated with its value.

student = ["James", "Tim", "Peter", "John"]

dict1 = {stu: 0 for stu in student}

print(dict1)

Output:

Python convert list to dictionary keys

Using zip() function

This function is used to zip the two values together. First, create an iterator and initialize to any variable and then typecast to the dict() function.

def get_dict(a):

    init = iter(list1)
    res_dct = dict(zip(init, init))
    return res_dct


list1 = ['x', 1, 'y', 2, 'z', 3]
print(get_dict(list1))

Output: {‘x’: 1, ‘y’: 2, ‘z’: 3}

Do comment if you have any doubts and suggestions on this Python list dictionary 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.