Convert Lists into Similar key value lists in Python

Converting two separate lists into a key-value mapping is a common data processing task in Python. The first list serves as keys, while the second list provides values. When keys repeat, their corresponding values are grouped together into lists.

Example Input and Output

keys = [3, 4, 3, 4, 5, 5]
values = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

# Expected output:
# {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Using defaultdict with zip()

The most efficient approach uses defaultdict to automatically create empty lists for new keys ?

from collections import defaultdict

keys = [3, 4, 3, 4, 5, 5]
values = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = defaultdict(list)

for key, value in zip(keys, values):
    result_dict[key].append(value)

result_dict = dict(result_dict)
print("Mapped dictionary:", result_dict)
Mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Using Regular Dictionary with Manual Check

This approach manually checks if a key exists before adding values ?

keys = [3, 4, 3, 4, 5, 5]
values = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = {}

for key, value in zip(keys, values):
    if key not in result_dict:
        result_dict[key] = []
    result_dict[key].append(value)

print("Mapped dictionary:", result_dict)
Mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Using setdefault() Method

The setdefault() method provides a clean one-liner solution ?

keys = [3, 4, 3, 4, 5, 5]
values = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = {}

for key, value in zip(keys, values):
    result_dict.setdefault(key, []).append(value)

print("Mapped dictionary:", result_dict)
Mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Using groupby() from itertools

For sorted data, groupby() offers an elegant functional approach ?

from itertools import groupby
from operator import itemgetter

keys = [3, 4, 3, 4, 5, 5]
values = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

# Sort pairs by key first
sorted_pairs = sorted(zip(keys, values), key=itemgetter(0))

# Group by key and extract values
result_dict = {key: [item[1] for item in group] 
               for key, group in groupby(sorted_pairs, key=itemgetter(0))}

print("Mapped dictionary:", result_dict)
Mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Comparison of Methods

Method Time Complexity Space Complexity Best For
defaultdict O(n) O(n) Most efficient, clean code
Manual check O(n) O(n) No imports needed
setdefault() O(n) O(n) Concise one-liner
groupby() O(n log n) O(n) When data is already sorted

Conclusion

Use defaultdict for the most efficient solution, or setdefault() for concise code without imports. The groupby() approach works well when your data is already sorted or when you need functional programming style.

Updated on: 2026-03-27T15:56:05+05:30

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements