Python Programming Examples Tutorial Index

Python Array Programs

Lists and dictionaries are two different mutable data structures in Python and are used as needed in code to store a collection or group of elements. Sometimes while coding, a situation arises where there is a need to convert two lists into one directory, which is explained in this tutorial on how to do it.

So first, create two sample data lists based on the students' data:

Keys = ["Student Name", "Role No.", "Subject"]
Values = ["Alex", "12345", "Python"]

In the above code, there are two lists containing keys and values. The keys have the head of the students' data, and the values have the student's actual data. Now here's how we can convert the two Python lists into a dictionary:


Keys = ["Student Name", "Role No.", "Subject"]
Values = ["Alex", "12345", "Python"]

StudentsData = dict(zip(Keys, Values))

Program Output:

{'Student Name': 'Alex', 'Role No.': '12345', 'Subject': 'Python'}

In the above code, the zip() function inside the dict() function stores both lists (Keys and Values) in the new dictionary. The zip() function is an in-built function that takes iterators (can be zero or more), aggregates and combines them, and returns them as an iterator of tuples and the dict() function creates a new dictionary.

Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram