Convert Lists into Similar key value lists in Python


Given 2 separate lists, we are going to transform them into a single data structure by mapping them into a key-value data structure namely dictionary. The values of the 1st list will serve as keys and values from the 2nd list will serve as values of the corresponding keys in the dictionary. The relationship can be considered as 1 to 1 or 1 to many i.e. 1 key can have multiple values.

Let us now see a sample input and output to better understand how we will be able convert Lists into Similar key value lists in Python in this article.

Input

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

Output

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

Method 1: Using a Defaultdict and Zip

This method makes use of defaultdict along with a list as the default value which helps to efficiently group elements from list2 by their corresponding elements in the 1st list which is list1. After that it converts the defaultdict into a regular dictionary for the sake of clarity thereby resulting in a mapped relationship of values from list1 to list of values from list2.

Example

from collections import defaultdict

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = defaultdict(list)

for key, value in zip(list1, list2):
   result_dict[key].append(value)

result_dict = dict(result_dict)
print("The first list is:",list1)
print("The second list is:",list2)
print("The mapped dictionary:",result_dict)

Output

The first list is: [3, 4, 3, 4, 5, 5]
The second list is: ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']
The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Method 2: Using a loop and an Empty Dictionary

This method formulates an empty dictionary named result_dict. For each pair, it evaluates if the key (an element from list1) is present in result_dict; if absent, it initializes this key with a vacant list. Subsequently, it annexes the corresponding value an element from list2 to its associated key's list: this effectively forms a dictionary where elements from list1 serve as keys; values, however, consist of lists comprising associated elements from list2.

Example

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = {}

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

print("The mapped dictionary:",result_dict)

Output

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Method 3: Using list Comprehension and Defaultdict

The defaultdict here automatically creates lists for each key-an element from list1; it then translates this defaultdict into an ordinary dictionary. The eventual outcome: a mapping where keys manifest as elements drawn from list1, and values emerge through lists of associated elements derived from list2.

Example

from collections import defaultdict

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = defaultdict(list)

[result_dict[key].append(value) for key, value in zip(list1, list2)]

result_dict = dict(result_dict)
print("The mapped dictionary:",result_dict)

Output

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Method 4: Using a Dictionary Comprehension

In Python, we can create dictionaries concisely through dictionary comprehensions. The code: "{key: [] for key in set(list1)}", constructs a dictionary with the unique elements from list1 act as keys; these are initialized with empty lists as values.

Example

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = {key: [] for key in set(list1)}

[result_dict[key].append(value) for key, value in zip(list1, list2)]
print("The mapped dictionary:",result_dict)

Output

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Method 5: Using a Defaultdict and itertools.groupby

The defaultdict(list) command activates a dictionary; this newly initiated dictionary awaits missing keys, all of which will be populated by empty lists. The groupby function classifies pairs according to the first value - lambda x: x[0] denotes the key for such grouping. Consequently, list1 and list2 elements undergo sorting and subsequent grouping into result_dict through executing this code segment.

Example

from collections import defaultdict
from itertools import groupby

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

sorted_lists = sorted(zip(list1,list2), key=lambda x: x[0])

result_dict = defaultdict(list)

for key, group in groupby(sorted_lists, key=lambda x: x[0]):
   result_dict[key].extend(item[1] for item in group)

result_dict = dict(result_dict)
print("The mapped dictionary:",result_dict)

Output

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Method 6: Using a Counter from the Collections Module

Employing a Counter, this code tallies the occurrences of elements within list1; it then cycles through both list1 and list2 with zip, a method that guarantees each key (an element from list1) aligns with an array of values (elements drawn from list2). With precision, the Counter maintains an up-to-date record for every usable instance per key: in doing so, we avoid replication in the resultant dictionary.

Example

from collections import Counter

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = {}
counter = Counter(list1)

for key, value in zip(list1, list2):
   if counter[key] > 0:
      if key not in result_dict:
         result_dict[key] = []
      result_dict[key].append(value)
      counter[key] -= 1
print("The mapped dictionary:",result_dict)

Output

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Method 7: Using a zip and itertools.groupby

This method 1st sorts the lists and then uses groupby to group the sorted pairs which forms a result_dict with keys from list 1 and values from list2.

Example

from itertools import groupby
from operator import itemgetter

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

sorted_lists = sorted(zip(list1,list2), key=itemgetter(0))

result_dict = {key: [x[1] for x in group] for key, group in groupby(sorted_lists, key=itemgetter(0))}

print("The mapped dictionary:",result_dict)

Output

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

Method 8: Using a for loop and setdefault

Iterating in parallel through two lists list1 and list2, the code melds them together using the zip function. It follows by creating a dictionary, result_dict; here, it assigns elements from list1 as keys and groupings of elements from list2 into lists as corresponding values. The setdefault method initializes any unprecedented dictionary keys, a procedure that ensures successful mapping between values on list1 to their associated sets of values on list2.

Example

list1 = [3, 4, 3, 4, 5, 3]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = {}

for key, value in zip(list1, list2):
   result_dict.setdefault(key, []).append(value)

print("The mapped dictionary:",result_dict)

Output

The mapped dictionary: {3: ['apple', 'cherry', 'fig'], 4: ['banana', 'date'], 5: ['elderberry']}

Method 9: Using the groupby function from itertools

This code amalgamates two lists: list1 and list2. Initially, it sorts them contingent on elements from list1; subsequently, itertools.groupby plays its part to group elements bearing identical keys - resulting in a dictionary labeled result_dict. Herein this directory, the unique elements derived from list1 serve as keys while their correlated components within List2 are employed as values.

Example

from itertools import groupby

list1 = [5, 0, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

sorted_lists = sorted(zip(list1, list2), key=lambda x: x[0])

result_dict = {key: [item[1] for item in group] for key, group in groupby(sorted_lists, key=lambda x: x[0])}

print("The mapped dictionary:",result_dict)

Output

The mapped dictionary: {0: ['banana'], 3: ['cherry'], 4: ['date'], 5: ['apple', 'elderberry', 'fig']}

Conclusion

We have shown different methods to creating a mapping dictionary for 2 separate lists. By establishing associations between elements in these lists, the codes demonstrate how to efficiently manage data; accommodating both 1-1 and 1-many relationships. Each method has its own pros and cons however understanding each 1 of them may help programmers get a better grasp of python.

Updated on: 02-Nov-2023

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements