When creating a python dict using two lists, how do I make it if the list of keys when a key has multiple values

Viewed 63
keys_list = ["a", "b", "c", "b"]
values_list = [1, 2, 3, 4]
zip_iterator = zip(keys_list, values_list)

a_dictionary = dict(zip_iterator)

print(a_dictionary)

This returns

{'a': 1, 'b': 4, 'c': 3}

But I want it to return

{'a': 1, 'b': 2, 4, 'c': 3}

How can I make this happen

3 Answers
from itertools import groupby
from operator import itemgetter

# Keys and values.
ks = ["a", "b", "c", "b"]
vs = [1, 2, 3, 4]

# Option 1: ordinary Python [recommended].
d1 = {}
for k, v in zip(ks, vs):
    d1.setdefault(k, []).append(v)

# Option 2: using groupby.
d2 = dict(
    (k, [v for k2, v in g])
    for k, g in groupby(sorted(zip(ks, vs)), itemgetter(0))
)

# Check.
print(d1 == d2, d1)   # True {'a': [1], 'b': [2, 4], 'c': [3]}
from collections import defaultdict
keys_list = ["a", "b", "c", "b"]
values_list = [1, 2, 3, 4]

d = defaultdict(list)

for k,v in zip(keys_list,values_list):
    d[k].append(v)

print(dict(d))

Output:

{'a': [1], 'b': [2, 4], 'c': [3]}

You can try this way. But you need a list or tuple to store multiple values.

>>> keys_list = ["a", "b", "c", "b"]
>>> values_list = [1, 2, 3, 4]
>>> res = {}
>>> for key, value in zip(keys_list, values_list):
...     try:
...             res[key].append(value)
...     except:
...             res[key] = []
...             res[key].append(value)
... 
>>> res
{'a': [1], 'b': [2, 4], 'c': [3]}
Related