Melina
Melina

Reputation: 303

combine two lists in a dictionary keep duplicate values of a key which has multi values

I want to combine two lists into a dictionary, but keep all values of each key. See my desired output:

Two lists:
a = ['E', 'AA', 'AA','AA', 'S', 'P']
b = ['11', '22', '33','44', '55', '66']

Output is a dictionary:
dict_1 = {'E': ['11'], 'AA': ['22', '33', '44'], 'S': ['55'], 'P': ['66']}

Problem:

I have the following code, after trying many times, I still only get an undesired output as follows (I have tried a whole afternoon):

Current undesired output:
dict_1 = {'E': ['11'], 'AA': ['44'], 'S': ['55'], 'P': ['66']}

My code:

a = ['E', 'AA', 'AA','AA', 'S', 'P']
b = ['11', '22', '33','44', '55', '66']
c = []
dict_1 = {}
i = 0
while i < 6:  
    j = i
    c = []
    while i<= j <6:        
        if a[i]==a[j]:
            c.append(b[j])             
        j+=1    
    dict_1[a[i]] = c
#    print(dict_1)
    i+=1        
print(dict_1)

New to Python, nothing elegant on coding. I only want to update it so that I can get my desired output. If anyone has a hint on it, please feel free to comment or answer. Thanks!

Upvotes: 2

Views: 311

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195438

You can use dict.setdefault:

a = ["E", "AA", "AA", "AA", "S", "P"]
b = ["11", "22", "33", "44", "55", "66"]

dict_1 = {}
for i, j in zip(a, b):
    dict_1.setdefault(i, []).append(j)

print(dict_1)

Prints:

{'E': ['11'], 'AA': ['22', '33', '44'], 'S': ['55'], 'P': ['66']}

Upvotes: 3

Related Questions