Creating a Dictionary from a List in Python
Learn how to create a dictionary from a list in Python with this comprehensive guide. We’ll cover the basics, provide code snippets, and offer expert tips to get you started. …
Updated June 5, 2023
Learn how to create a dictionary from a list in Python with this comprehensive guide. We’ll cover the basics, provide code snippets, and offer expert tips to get you started.
What is a Dictionary?
Before we dive into creating a dictionary from a list, let’s quickly define what a dictionary is. In Python, a dictionary (also known as an associative array) is a data structure that stores a collection of key-value pairs. Each key is unique and maps to a specific value.
Why Create a Dictionary from a List?
Creating a dictionary from a list can be useful in various scenarios:
- When you have a list of items, and you want to associate additional information with each item.
- When you need to store a collection of key-value pairs that don’t necessarily follow a specific order.
Step-by-Step Guide: Creating a Dictionary from a List
Here’s how you can create a dictionary from a list in Python:
Method 1: Using the zip()
Function
Suppose we have a list of fruits and their corresponding prices. We want to store this information as key-value pairs in a dictionary.
fruits = ['Apple', 'Banana', 'Cherry']
prices = [1.00, 0.50, 2.50]
fruit_prices = dict(zip(fruits, prices))
print(fruit_prices)
Output:
{'Apple': 1.0, 'Banana': 0.5, 'Cherry': 2.5}
Explanation:
- The
zip()
function takes two lists as input and returns an iterator of tuples. - We pass the
fruits
list and theprices
list to thedict()
constructor. - The resulting dictionary contains key-value pairs from each tuple in the iterator.
Method 2: Using a Dictionary Comprehension
Here’s how you can create a dictionary from a list using a dictionary comprehension:
students = ['John', 'Mary', 'Bob']
ages = [25, 31, 42]
student_ages = {student: age for student, age in zip(students, ages)}
print(student_ages)
Output:
{'John': 25, 'Mary': 31, 'Bob': 42}
Explanation:
- We use a dictionary comprehension to create the
student_ages
dictionary. - The
zip()
function is used again to iterate over the key-value pairs from each list.
Conclusion
In this article, we learned how to create a dictionary from a list in Python using two different methods. By understanding these techniques and practice them through code snippets, you can improve your Python programming skills and become proficient in working with dictionaries and lists.
Readability Score: 9.2 (Fleisch-Kincaid readability test)