0
0
Pythonprogramming~5 mins

Creating dictionary from two sequences in Python

Choose your learning style9 modes available
Introduction
We use this to pair items from two lists or sequences into a dictionary, making it easy to look up values by keys.
You have a list of names and a list of phone numbers and want to link each name to its phone number.
You want to combine two lists, like countries and their capitals, into a dictionary for quick access.
You have two sequences of related data and want to organize them as key-value pairs.
You want to convert two separate lists into one dictionary for easier data handling.
Syntax
Python
dictionary = dict(zip(sequence1, sequence2))
The zip() function pairs items from both sequences one by one.
dict() converts these pairs into a dictionary.
Examples
Creates a dictionary {'a': 1, 'b': 2, 'c': 3} by pairing keys and values.
Python
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))
print(d)
Pairs fruit names with their colors in a dictionary.
Python
fruits = ['apple', 'banana']
colors = ['red', 'yellow']
fruit_colors = dict(zip(fruits, colors))
print(fruit_colors)
Maps numbers to their squares using two lists.
Python
numbers = [1, 2, 3]
squares = [1, 4, 9]
square_dict = dict(zip(numbers, squares))
print(square_dict)
Sample Program
This program creates a dictionary linking each person's name to their age.
Python
names = ['John', 'Jane', 'Doe']
ages = [25, 30, 22]
people_ages = dict(zip(names, ages))
print(people_ages)
OutputSuccess
Important Notes
If the sequences have different lengths, zip stops at the shortest one.
Keys in a dictionary must be unique; if duplicates exist in the first sequence, later values overwrite earlier ones.
Summary
Use zip() to pair items from two sequences.
Convert the pairs to a dictionary with dict().
This method helps organize related data simply and clearly.