Introduction
In Python, you can easily convert two lists into a dictionary, where one list contains the keys and the other contains the corresponding values. This is useful when you have related data that you want to pair together in a structured way. This tutorial will guide you through creating a Python program that converts two lists into a dictionary.
Example:
- Input Lists:
- Keys:
['name', 'city', 'nationality'] - Values:
['Ramesh', 'Pune', 'Indian']
- Keys:
- Output Dictionary:
{'name': 'Ramesh', 'city': 'Pune', 'nationality': 'Indian'}
Problem Statement
Create a Python program that:
- Takes two lists as input.
- Converts the lists into a dictionary where one list contains the keys and the other contains the values.
- Displays the resulting dictionary.
Solution Steps
- Create Two Lists: Initialize two lists, one for the keys and one for the values.
- Convert Lists to Dictionary: Use the
zip()function anddict()constructor to combine the two lists into a dictionary. - Display the Dictionary: Use the
print()function to display the resulting dictionary.
Python Program
# Python Program to Convert Two Lists into a Dictionary
# Author: https://www.rameshfadatare.com/
# Step 1: Create two lists, one for keys and one for values
keys = ['name', 'city', 'nationality']
values = ['Ramesh', 'Pune', 'Indian']
# Step 2: Convert the two lists into a dictionary
my_dict = dict(zip(keys, values))
# Step 3: Display the resulting dictionary
print("The resulting dictionary is:", my_dict)
Explanation
Step 1: Create Two Lists, One for Keys and One for Values
- Two lists are created:
keyscontaining the keys (['name', 'city', 'nationality']) andvaluescontaining the corresponding values (['Ramesh', 'Pune', 'Indian']).
Step 2: Convert the Two Lists into a Dictionary
- The
zip()function is used to pair elements from thekeyslist with elements from thevalueslist, creating pairs like('name', 'Ramesh'). Thedict()constructor then converts these pairs into a dictionary.
Step 3: Display the Resulting Dictionary
- The
print()function is used to display the resulting dictionary.
Output Example
Example Output:
The resulting dictionary is: {'name': 'Ramesh', 'city': 'Pune', 'nationality': 'Indian'}
Conclusion
This Python program demonstrates how to convert two lists into a dictionary using the zip() function and dict() constructor. This method is efficient and straightforward, making it ideal for pairing related data. Understanding this process is essential for handling structured data and creating dictionaries dynamically from lists.