Vladislav Ladenkov Vladislav Ladenkov - 4 months ago 8
Python Question

What is the best way sort 2-D list and transform it to dictionary

The question is much more trivial then it sounds.
I have 2-D

[2xn]
array with keys in the first column(which repeat) and values in the second. I need to make a dictionary , where keys- are uniqe keys, and there values are collected from the values. What is the smartest way to do it? Shall i first preprocess( sort keys-values in groups or smth ) or shall i put a
set(keys)
to dictionary keys and then operate with values there? Or, maybe, shall i put
keys
and
values
lists in dictionary and "squeze" it already in dictionary!? Thanks!
Input:
Isis 3
Isis 4
Al-Qaeda 2
Isis 2
Desired output:
{'Isis':[3,4,2], 'Al-Qaeda':[2]}

Answer

Use a defaultdict:

from collections import defaultdict

output = defaultdict(list)
for k,v in input:
    output[k].append(v)