0

I want to convert list to a dictionary that will have duplicate keys so to have all values I would like to have a list of values within a dict.

input as list:

l = ['a', '1', 'b', '2', 'a', '3']

Output should look like this:

d = {'a': ['1','3'], 'b': '2' }
yatu
  • 86,083
  • 12
  • 84
  • 139
ripz
  • 1

2 Answers2

0

Try this

res = {}
for i in range(0, len(l), 2):
    res.setdefault(l[i], []).append(l[i+1])
print(res)

Output:

{'a': ['1', '3'], 'b': ['2']}

You can also use zip()

res = {}
for k, v in zip(l[0::2], l[1::2]):
    res.setdefault(k, []).append(v)
deadshot
  • 8,881
  • 4
  • 20
  • 39
0
from collections import defaultdict

d = defaultdict(list)
l = ['a', '1', 'b', '2', 'a', '3']
for idx,x in enumerate(l):
    if idx % 2 != 0:
        d[l[idx-1]].append(x)
print(d)

output

defaultdict(<class 'list'>, {'a': ['1', '3'], 'b': ['2']})
balderman
  • 22,927
  • 7
  • 34
  • 52