If I have a list that looks like this:
['1 184',
'1 29',
'1 31',
'1 12',
'1 51',
'1 102',
'1 13',
'1 14',
'1 15',
'1 57',
'1 378',
'1 859',
'1 185',
'1 30',
'1 37',
'1 52',
'1 142',
'1 195',
'1 875',
'1 56',
'1 66',
'1 95',
'1 462',
'1 497',
'1 858',
'1 876',
'1 879',
'1 880',
'2 12',
'2 15',
'2 184',
'2 858',
'2 51']
And I wanted to map the first element of each string to each of the next elements tied to that first number, and get it in the format of {1 : [184, 29, 31...], 2 : [12, 15, 18, ...]}.
How could I do that?
>Solution :
If lst is your list from your question then:
out = {}
for a, b in map(str.split, lst):
out.setdefault(int(a), []).append(int(b))
print(out)
Prints:
{
1: [
184,
29,
31,
12,
51,
102,
13,
14,
15,
57,
378,
859,
185,
30,
37,
52,
142,
195,
875,
56,
66,
95,
462,
497,
858,
876,
879,
880,
],
2: [12, 15, 184, 858, 51],
}
EDIT: To explicitly check for correct values:
out = {}
for value in lst:
value = value.split()
if len(value) == 2:
a, b = value
out.setdefault(int(a), []).append(int(b))