|
| Home |
|---|
In Python programming, lists and dictionaries are two commonly used data structures. A list stores values in order, while a dictionary stores data in the form of key–value pairs.
Sometimes data is stored in a list but needs to be converted into a dictionary so that values can be accessed using keys. Python provides several ways to convert lists into dictionaries.
A Python dictionary stores data as key-value pairs. Each key is associated with a specific value.
student = {
"name": "Ali",
"age": 20
}
print(student)
{'name': 'Ali', 'age': 20}
If a list contains tuples where each tuple has two elements, it can easily be converted into a dictionary.
data = [("name","Ali"),("age",20),("city","Lahore")]
dictionary = dict(data)
print(dictionary)
{'name': 'Ali', 'age': 20, 'city': 'Lahore'}
Two separate lists can be converted into a dictionary using
the zip() function.
keys = ["name","age","city"]
values = ["Ali",20,"Lahore"]
dictionary = dict(zip(keys, values))
print(dictionary)
{'name': 'Ali', 'age': 20, 'city': 'Lahore'}
Lists can also be converted into dictionaries manually using a loop.
keys = ["a","b","c"]
values = [1,2,3]
dictionary = {}
for i in range(len(keys)):
dictionary[keys[i]] = values[i]
print(dictionary)
{'a': 1, 'b': 2, 'c': 3}
Dictionary comprehension provides a concise way to create dictionaries from lists.
keys = ["x","y","z"]
values = [10,20,30]
dictionary = {k:v for k,v in zip(keys, values)}
print(dictionary)
{'x': 10, 'y': 20, 'z': 30}
Sometimes numbers in a list can be converted into dictionary values with indexes as keys.
numbers = [10,20,30]
dictionary = {i:numbers[i] for i in range(len(numbers))}
print(dictionary)
{0: 10, 1: 20, 2: 30}
Lists can be converted into dictionaries in Python using several
methods such as dict(), zip(),
loops, or dictionary comprehension.
The zip() function combined with dict()
is one of the most common and efficient ways to perform this conversion.
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net