Python Program to Convert Two Lists Into a Dictionary
In Python, a list is a collection of ordered elements, and it is mutable (i.e., we can modify the elements of a list). A list can contain elements of different data types such as integers, strings, or even other lists.
For example, we can create a list of integers as follows:
my_list = [1, 2, 3, 4, 5]
A dictionary, on the other hand, is an unordered collection of key-value pairs, and it is also mutable. Each key in a dictionary maps to a value. The keys are unique and immutable, which means they cannot be changed once created. The values can be of any data type such as integers, strings, or even other dictionaries.
For example, we can create a dictionary of strings as follows:
my_dict = {'apple': 'red', 'banana': 'yellow', 'orange': 'orange'}
In Python, both lists and dictionaries are very useful for storing and manipulating data.
Python Code :
The below Python program converts two lists into a dictionary:
# Define two lists
keys = ["a", "b", "c"]
values = [1, 2, 3]
# Use the zip() function to combine the lists into a dictionary
my_dict = dict(zip(keys, values))
# Print the resulting dictionary
print(my_dict)
In this program, we first define two lists keys and values, which we want to convert into a dictionary.
We then use the zip() function to combine the two lists into a single iterable of tuples, where each tuple contains a key-value pair. We pass the keys and values lists as arguments to the zip() function.
Finally, we convert the iterable of tuples into a dictionary using the dict() constructor, and assign the resulting dictionary to the variable my_dict. We then print the resulting dictionary.
Note that if the two lists are not the same length, the resulting dictionary will only contain the key-value pairs up to the length of the shorter list.