Skip to content Skip to sidebar Skip to footer

A Better Way To Create A Dictionary Out Of Two Lists With Duplicated Values In One

I have two lists: a = ['A', 'B', 'B', 'C', 'D', 'A'] b = [1, 2, 3, 4, 5, 6] I want to have a dictionary like the one below: d = {'A':[1, 6], 'B':[2, 3], 'C':[4], 'D':[5]} Right n

Solution 1:

You can use the dict.setdefault method to initialize each key as a list and then append the current value to it while you iterate:

d = {}
for k, v in zip(a, b):
    d.setdefault(k, []).append(v)

With the sample input, d would become:

{'A': [1, 6], 'B': [2, 3], 'C': [4], 'D': [5]}

Solution 2:

Running your code, didnt produce the output what you wanted. The below is a bit more verbose but makes it easy to see what the code is doing.

a = ["A", "B", "B", "C", "D", "A"]
b = [1, 2, 3, 4, 5, 6]
c = {}

for a, b in zip(a, b):
    if a in c:
        if isinstance(a, list):
            c[a].append(b)
        else:
            c[a] = [c[a], b]
    else:
        c[a] = b

print(c)

OUTPUT

{'A': [1, 6], 'B': [2, 3], 'C': 4, 'D': 5}

An alternative less verbose mode would be to use a default dict with list as the type, you can then append all the items to it. this will mean even single items will be in a list. to me its much cleaner as you will know the data type of each item in the list. However if you really do want to have single items not in a list you can clean it up with a dict comprehension

from collections import defaultdict
a = ["A", "B", "B", "C", "D", "A"]
b = [1, 2, 3, 4, 5, 6]
c = defaultdict(list)

for a, b in zip(a, b):
    c[a].append(b)

d = {k: v if len(v) > 1 else v[0] for k, v in c.items()}
print(c)
print(d)

OUTPUT

defaultdict(<class 'list'>, {'A': [1, 6], 'B': [2, 3], 'C': [4], 'D': [5]})
{'A': [1, 6], 'B': [2, 3], 'C': 4, 'D': 5}

Post a Comment for "A Better Way To Create A Dictionary Out Of Two Lists With Duplicated Values In One"