🔄 Converting Between Lists and Dictionaries
Python provides multiple ways to convert between lists and dictionaries. Understanding these transformations is essential for data manipulation and format conversion.
# Basic list to dictionary conversion
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']
person = dict(zip(keys, values))
print(person) # {'name': 'Alice', 'age': 25, 'city': 'New York'}
🎯 Conversion Methods
Python offers several approaches to convert between lists and dictionaries.
Basic Examples
# Different conversion patterns
# List to Dictionary
fruits = ['apple', 'banana', 'cherry']
prices = [1.0, 2.0, 3.0]
# Using zip
fruit_prices = dict(zip(fruits, prices))
print(f"Fruit prices: {fruit_prices}")
# Using enumerate
fruit_indices = dict(enumerate(fruits))
print(f"Fruit indices: {fruit_indices}")
# Using comprehension
fruit_lengths = {fruit: len(fruit) for fruit in fruits}
print(f"Fruit lengths: {fruit_lengths}")
# Dictionary to Lists
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
keys = list(person.keys())
values = list(person.values())
items = list(person.items())
print(f"Keys: {keys}")
print(f"Values: {values}")
print(f"Items: {items}")
🔍 Advanced Conversions
Python allows more sophisticated conversion operations.
# Advanced conversion examples
# Nested list to dictionary
data = [['name', 'Alice'], ['age', 25], ['city', 'New York']]
person = dict(data)
print(f"From nested list: {person}")
# List of tuples to dictionary
tuples = [('a', 1), ('b', 2), ('c', 3)]
letters = dict(tuples)
print(f"From tuples: {letters}")
# Dictionary to list of dictionaries
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
student_list = [{'name': name, 'score': score}
for name, score in scores.items()]
print(f"Student list: {student_list}")
# Flattening dictionary to list
flat_list = [item for pair in scores.items() for item in pair]
print(f"Flattened: {flat_list}")
# Grouping list items into dictionary
students = ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob']
grouped = {}
for student in students:
if student in grouped:
grouped[student] += 1
else:
grouped[student] = 1
print(f"Grouped: {grouped}")
# Using collections.Counter
from collections import Counter
counted = dict(Counter(students))
print(f"Counted: {counted}")
🎯 Key Takeaways
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.