How can i turn a list into a dict getting something like this?

Question:

I have a list like this:

enter image description here

how to get something like this?

enter image description here

Asked By: Juliano Silva

||

Answers:

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]}
Answered By: Samwise
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.