Skip to content

Python convert list to dictionary keys | Example code

  • by

Using Dictionary Comprehension or zip() function will convert the 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 to 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 a 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 it 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 or suggestions on this Python list dictionary 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