-2

I have two lists:

list_1 = ['2', '1', '1', '2', '1', '2', '1', '5', '4', '3', '2', '1', '3', '2', '1']
list_2 = ['az', 'z', 'c', 'bo', 'o', 'bo', 'o', 'beggh', 'eggh', 'ggh', 'gh', 'h', 'akl', 'kl', 'l']

The number of strings inside the two lists is the same. I want to create a dictionary from the two lists, so I try:

new_dict = dict(zip(list_1, list_2))

I expect something like:

{
  '2' : 'az',
  '1' : 'z',
  '1' : 'c',
  ....


}

I also expect that the number of key-value pairs in the dictionary is the same as the number of strings in either list_1 or list_2. However, when I try to print the dictionary out, it gives:

{'2': 'kl', '1': 'l', '5': 'beggh', '4': 'eggh', '3': 'akl'}

The number of key-value pairs is only 5, which is obviously less than the number of strings in either list_1 or list_2. What has gone wrong?

Dennis
  • 175
  • 1
  • 3
  • 8

1 Answers1

3

You cannot have a dictionary with duplicated keys, one solution would be to group values by key, here an example using itertools.groupby

from itertools import groupby
list_1 = ['2', '1', '1', '2', '1', '2', '1', '5', '4', '3', '2', '1', '3', '2', '1']
list_2 = ['az', 'z', 'c', 'bo', 'o', 'bo', 'o', 'beggh', 'eggh', 'ggh', 'gh', 'h', 'akl', 'kl', 'l']

new_dict = {
    k : list(map(lambda x: x[1], v)) for k, v in groupby(sorted(zip(list_1, list_2)), key=lambda x: x[0])
}
print(new_dict)

Live example

Or simply use a defaultdict

from collections import defaultdict
new_dict = defaultdict(list)
for k, v in zip(list_1, list_2):
    new_dict[k].append(v)
Netwave
  • 40,134
  • 6
  • 50
  • 93