Home > Software engineering >  How can i turn a list into a dict getting something like this?
How can i turn a list into a dict getting something like this?

Time:10-30

I have a list like this:

enter image description here

how to get something like this?

enter image description here

CodePudding user response:

Start with an empty dict, iterate over the list, and append each value to a list in the dict, creating it if needed.

>>> a_list = [['a', 1], ['b', 18], ['a', 3], ['b', 21], ['a', 51], ['b', 88]]
>>> a_dict = {}
>>> for k, v in a_list:
...     a_dict.setdefault(k, []).append(v)
...
>>> a_dict
{'a': [1, 3, 51], 'b': [18, 21, 88]}
  • Related