Robert
Robert

Reputation: 33

Removing duplicate keys from python dictionary but concatenating the values of duplicated keys

Let's say I have two lists:

lista = ['winter', 'fall', 'spring', 'summer', 'winter', 'spring']
listb = ['cold', 'rainy', 'windy', 'hot', 'chilly', 'wet']

I want to create a dictionary that pulls the unique values from lista as the key (which it will do automatically since dictionaries can only have unique keys) and the values from list b as the dictionary value, corresponding to lista by their order. So to create the dictionary I would do:

mydict = {k: v for k, v in zip(lista, listb)}

If I print this, I get:

{'winter': 'chilly', 'fall': 'rainy', 'spring': 'wet', 'summer': 'hot'}

However, what I would like to do, is for every "key" from lista that is duplicate, I'd like to concatenate the values from listb to be the "value" in the dictionary as a list. So the goal would be:

{'winter': ['cold', 'chilly'], 'fall': ['rainy'], 'spring': ['windy', 'wet'], 'summer': ['hot']}

This is a dumbed down version of what I am trying to do but I think it applies - I am reading a csv file and trying to make the "last name" column the key, and every other row the value (as a list). So far I've created a list for last names and the list for the other rows, but I need to concatenate the values for duplicate names.

Upvotes: 2

Views: 157

Answers (2)

cody
cody

Reputation: 11157

There's no need to explicitly initialize the values with empty lists, use defaultdict:

from collections import defaultdict

lista = ['winter', 'fall', 'spring', 'summer', 'winter', 'spring']
listb = ['cold', 'rainy', 'windy', 'hot', 'chilly', 'wet']

d = defaultdict(list)
for x, y in zip(lista, listb):
    d[x].append(y)

print(dict(d))

Note that it's not necessary to cast to dict as I did, as defaultdict is a subclass of dict. I just did it so the output would match your requirements exactly.

Result:

{'winter': ['cold', 'chilly'], 'fall': ['rainy'], 'spring': ['windy', 'wet'], 'summer': ['hot']}

Upvotes: 2

Elie Louis
Elie Louis

Reputation: 109

How about this?

lista = ['winter', 'fall', 'spring', 'summer', 'winter', 'spring']
listb = ['cold', 'rainy', 'windy', 'hot', 'chilly', 'wet']
mydict = {k : [] for k in lista}
for k,v in zip(lista, listb):
    mydict[k].append(v)

Upvotes: 0

Related Questions