Home > Software engineering >  Python3 How can I convert list to dict
Python3 How can I convert list to dict

Time:02-24

I have a list like: lst=[['a',1],['b',2],['a',3],['b',1],['a',1]]

how can I convert this to dictionary like that: dct={'a':[1,3,1],'b':[2,1]}

CodePudding user response:

The default dictionary can help you

from collections import defaultdict

ddict = defaultdict(list)

data = [['a',1],['b',2],['a',3],['b',1],['a',1]]
for key, value in data:
    ddict[key].append(value)

CodePudding user response:

Try this:

lst = [['a',1],['b',2],['a',3],['b',1],['a',1]]
dct = {}
for [k, v] in lst:
    dct[k] = dct[k]   [v] if k in dct else [v]
  • Related