0
0
PythonHow-ToBeginner · 2 min read

Python How to Convert Two Lists to Dictionary Easily

You can convert two lists to a dictionary in Python by using dict(zip(list1, list2)), which pairs elements from both lists as key-value pairs.
📋

Examples

Inputlist1 = ['a', 'b'], list2 = [1, 2]
Output{'a': 1, 'b': 2}
Inputlist1 = ['name', 'age'], list2 = ['Alice', 30]
Output{'name': 'Alice', 'age': 30}
Inputlist1 = [], list2 = []
Output{}
🧠

How to Think About It

To convert two lists into a dictionary, think of matching each item in the first list as a key with the corresponding item in the second list as its value. You pair them one by one and then create a dictionary from these pairs.
📐

Algorithm

1
Take the first list as keys.
2
Take the second list as values.
3
Pair each key with its corresponding value.
4
Create a dictionary from these pairs.
5
Return the dictionary.
💻

Code

python
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
dictionary = dict(zip(list1, list2))
print(dictionary)
Output
{'a': 1, 'b': 2, 'c': 3}
🔍

Dry Run

Let's trace converting list1 = ['a', 'b', 'c'] and list2 = [1, 2, 3] into a dictionary.

1

Pair elements

Pairs formed: ('a', 1), ('b', 2), ('c', 3)

2

Create dictionary

Dictionary created: {'a': 1, 'b': 2, 'c': 3}

KeyValue
'a'1
'b'2
'c'3
💡

Why This Works

Step 1: Using zip

The zip function pairs elements from two lists by their positions, creating pairs like (key, value).

Step 2: Creating dictionary

The dict function takes these pairs and makes a dictionary where the first item is the key and the second is the value.

🔄

Alternative Approaches

Using dictionary comprehension
python
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
dictionary = {list1[i]: list2[i] for i in range(len(list1))}
print(dictionary)
This method is clear and flexible but requires both lists to be the same length.
Using a loop
python
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
dictionary = {}
for i in range(len(list1)):
    dictionary[list1[i]] = list2[i]
print(dictionary)
This is more verbose but easy to understand for beginners.

Complexity: O(n) time, O(n) space

Time Complexity

The process loops through both lists once to pair elements, so it takes linear time proportional to the list size.

Space Complexity

A new dictionary is created with as many entries as the length of the lists, so space grows linearly.

Which Approach is Fastest?

Using dict(zip()) is the fastest and most readable; dictionary comprehension and loops are slightly slower but offer more control.

ApproachTimeSpaceBest For
dict(zip())O(n)O(n)Simple and fast conversion
Dictionary comprehensionO(n)O(n)When you want more control or conditions
Loop with assignmentO(n)O(n)Beginners learning step-by-step
💡
Make sure both lists have the same length to avoid missing or extra keys or values.
⚠️
Trying to convert lists of different lengths without handling mismatches causes missing or unexpected dictionary entries.