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
  • 112,593
  • 23
  • 157
  • 280
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 Mar 07 '21 at 20:58
  • "Show me how to solve this coding problem" is [off-topic for Stack Overflow](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question). You're expected to make an [honest attempt at the solution](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), and _then_ ask specific question(s) about your implementation. – martineau Mar 07 '21 at 21:17

2 Answers2

4

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,647
  • 2
  • 9
  • 18
1

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
  • 10,555
  • 2
  • 17
  • 39