How to create a dictionary merging two lists?
Creating dictionary by merging two lists is not a very hard thing. I am going to show three different methods to create a dictionary by merging two lists.
Let's first create two list:
items = ['books', 'pen', 'pencil', 'chair', 'notebooks']
price = [300, 100, 50, 800, 900]
We are going to use these lists in all three solutions.
Solution 1: Using Zip
and Dict
Method
We are going to use zip
method to zip or bind those two lists together and then we use dict
method to convert the zipped list into a dictionary. After that we will save this dictionary
into item_dict
variable and print
it
1# Items you bought
2items = ['books', 'pen', 'pencil', 'chair', 'notebooks']
3
4# Price of each item you paid
5price = [300, 100, 50, 800, 900]
6
7# Creating dictionary
8item_dict = dict(zip(items, qty, price))
9
10print(item_dict)
The output you receive after printing item_dict
variable this:
{'books': 300, 'pen': 100, 'pencil': 50, 'chair': 800, 'notebooks': 900}
Solution 2: Using Dictionary Comprehension
In this solution we are using dictionary comprehension
to pair key and value together and also zip
method to bind those two lists together.
1# Creating item list
2items = ['books', 'pen', 'pencil', 'chair', 'notebooks']
3
4# Creating price list
5price = [300, 100, 50, 800, 900]
6
7# Merging lists into a dictionary
8item_list = {key:value for key,value in zip(items,price)}
9
10print(item_list)
The output will be same as before:
{'books': 300, 'pen': 100, 'pencil': 50, 'chair': 800, 'notebooks': 900}
Solution 3: Using For-in loop
Here we are using our old for in loop
. We will create a blank dictionary item_list
and then use for
loop adding those two lists values in the item_list
dictionary
.
1# Creating item list
2items = ['books', 'pen', 'pencil', 'chair', 'notebooks']
3
4# Creating price list
5price = [300, 100, 50, 800, 900]
6
7# Merging lists into a dictionary
8item_list = {}
9
10for i in range(len(items)):
11 item_list[items[i]] = price[i]
12
13print(item_list)
And here also our output will be same as before.
{'books': 300, 'pen': 100, 'pencil': 50, 'chair': 800, 'notebooks': 900}
This is how we can merge two lists and create a dictionary out of it.