Skip to content Skip to sidebar Skip to footer

How To Handle Multiple Keys For A Dictionary In Python?

I've been searching about how to go for adding multiple val for single keys in a Dict if a duplicate key is found. Let's take an example: list_1 = ['4', '6' ,'8', '8'] list_2 = ['a

Solution 1:

defaultdict/dict.setdefault

Let's jump into it:

  1. Iterate over items consecutively
  2. Append string values belonging to the same key
  3. Once done, iterate over each key-value pair and join everything together for your final result.

from collections import defaultdict

d = defaultdict(list)   
for i, j in zip(list_1, list_2):
    d[i].append(j)

The defaultdict makes things simple, and is efficient with appending. If you don't want to use a defaultdict, use dict.setdefault instead (but this is a bit more inefficient):

d = {}
for i, j in zip(list_1, list_2):
    d.setdefault(i, []).append(j)

new_dict = {k : ','.join(v) for k, v in d.items()})
print(new_dict)
{'4': 'a', '6': 'b', '8': 'c,d'}

Pandas DataFrame.groupby + agg

If you want performance at high volumes, try using pandas:

import pandas as pd

df = pd.DataFrame({'A' : list_1, 'B' : list_2})
new_dict = df.groupby('A').B.agg(','.join).to_dict()

print(new_dict)
{'4': 'a', '6': 'b', '8': 'c,d'}

Solution 2:

You can do it with a for loop that iterates over the two lists:

list_1 = ['4', '6' ,'8', '8']
list_2 = ['a', 'b', 'c', 'd']

new_dict = {}
for k, v in zip(list_1, list_2):
    if k in new_dict:
        new_dict[k] += ', ' + v
    else:
        new_dict[k] = v

There might be efficiency problems for huge dictionaries, but it will work just fine in simple cases.

Thanks to @Ev. Kounis and @bruno desthuilliers that pointed out a few improvements to the original answer.


coldspeed's answer is more efficient than mine, I keep this one here because it is still correct and I don't see the point in deleting it.


Solution 3:

Try using setdefault dictionary function and get the index of it, then use try and except for checking if idx exists or not, i didn't get the index of the element every time because there are duplicates and at the end i format it so it outputs like Your desired output:

new_dict = {}
list_1 = ['4', '6' ,'8', '8']
list_2 = ['a', 'b', 'c', 'd']
for i in list_1:
   try:
      idx+=1
   except:
      idx = list_1.index(i)
   new_dict.setdefault(i, []).append(list_2[idx])
print({k:', '.join(v) for k,v in new_dict.items()})

Output:

{'4': 'a', '6': 'b', '8': 'c, d'}

Post a Comment for "How To Handle Multiple Keys For A Dictionary In Python?"