user1189851
user1189851

Reputation: 5041

Python list to dict

I have a huge list like

['a', '2'] ['a', '1'] ['b', '3'] ['c', '2'] ['b', '1'] ['a', '1']['b', '1'] ['c', '2']['b', '3'] ['b', '1']

I want to walk through this and get an output of number of each second item for a distinct first item:

{a:[2,1,1] b:[3,1,3,1] c:[2,2]}

Upvotes: 3

Views: 4144

Answers (3)

Jon Clements
Jon Clements

Reputation: 142136

from collections import defaultdict

dd = defaultdict(list)
for k, v in your_list:
    dd[k].append(v)

Alternatively your data is already sorted (remove the sorted step - or is otherwise okay to sort...)

from itertools import groupby
from operator import itemgetter
print {k: [v[1] for v in g] for k, g in groupby(sorted(d), itemgetter(0))}

Upvotes: 5

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

You can use collections.defaultdict here:

>>> from collections import defaultdict
>>> lis = [['a', '2'], ['a', '1'], ['b', '3'], ['c', '2'], ['b', '1'], ['a', '1'],['b', '1'], ['c', '2'],['b', '3'], ['b', '1']]
>>> dic = defaultdict(list)
>>> for k,v in lis:
       dic[k].append(int(v))
>>> dic
defaultdict(<type 'list'>, {'a': [2, 1, 1], 'c': [2, 2], 'b': [3, 1, 1, 3, 1]})
>>> dic['b']
[3, 1, 1, 3, 1]
>>> dic['a']
[2, 1, 1]

Upvotes: 3

Andrew Clark
Andrew Clark

Reputation: 208455

data = [['a','2'],['a','1'],['b','3'],['c','2'],['b','1'],['a','1'],['b','1'],['c','2'],['b','3'],['b','1']]
result = {}
for key, value in data:
    result.setdefault(key, []).append(value)

Outcome:

>>> result
{'a': ['2', '1', '1'], 'c': ['2', '2'], 'b': ['3', '1', '1', '3', '1']}

I prefer dict.setdefault() over defaultdict because you end up with a normal dictionary, where attempting to access a key that doesn't exist raises an exception instead of giving a value (in this case an empty list).

Upvotes: 11

Related Questions