1

I have a list with schema as shown below:

list=[('a',2),('b',4),('a',1),('c',6)]

What I would like to do is convert it to a dict using the first value of each pair as key,I would also like pairs with the same key to be concatenated.For the above the result would be:

dict={ 'a':[2,1] , 'b':[4] , 'c':[6]  }

I don't care about the order of the concatenated values,meaning we could also have 'a':[1,2].

How could this be done in python?

martineau
  • 119,623
  • 25
  • 170
  • 301
arxidiaris
  • 27
  • 1
  • You can use a `for` loop to iterate through the list and create the dictionary. If a key exists, append the element to the key value. Else create an entry to the dictionary with an one element list. `defaultdict` can also come in handy, to avoid many `if-else` conditions – Zois Tasoulas Mar 07 '21 at 20:58

2 Answers2

5

Do this:

l = [('a',2),('b',4),('a',1),('c',6)]

d = {}

for item in l:
    if item[0] in d:
        d[item[0]].append(item[1])
    else:
        d[item[0]] = [item[1]]

print(d) # {'a': [2, 1], 'b': [4], 'c': [6]}

To make it cleaner you could use defaultdict and 2 for iterators:

from collections import defaultdict

l = [('a',2),('b',4),('a',1),('c',6)]

d = defaultdict(lambda: [])

for key, val in l:
    d[key].append(val)

print(dict(d)) # {'a': [2, 1], 'b': [4], 'c': [6]})
lnogueir
  • 1,859
  • 2
  • 10
  • 21
2

You can also use the setdefault method on dict to set a list as the default entry if a key is not in the dictionary yet:

l=[('a',2),('b',4),('a',1),('c',6)]
d = {}

for k, v in l:
    d.setdefault(k, []).append(v)

d
{'a': [2, 1], 'b': [4], 'c': [6]}
C.Nivs
  • 12,353
  • 2
  • 19
  • 44