Python Program to Convert Two Lists into a Dictionary

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']
  • 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

  1. Create Two Lists: Initialize two lists, one for the keys and one for the values.
  2. Convert Lists to Dictionary: Use the zip() function and dict() constructor to combine the two lists into a dictionary.
  3. 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: keys containing the keys (['name', 'city', 'nationality']) and values containing the corresponding values (['Ramesh', 'Pune', 'Indian']).

Step 2: Convert the Two Lists into a Dictionary

  • The zip() function is used to pair elements from the keys list with elements from the values list, creating pairs like ('name', 'Ramesh'). The dict() 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top