Python, list of tuples split into dictionaries
You don't need to iterate the list twice. You can use setdefault()
to set the initial value if the key is not in the dictionary:
lt = [(1,'a'),(1,'b'),(2,'a'),(3,'b'),(3,'c')]
d = {}
for k, v in lt:
d.setdefault(k, []).append(v)
print(d)
prints
{1: ['a', 'b'], 2: ['a'], 3: ['b', 'c']}
You can use collections.defaultdict
with list
factory or dict.setdefault
to create a list that you can append the values to.
collections.defaultdict
:
out = collections.defaultdict(list)
for k, v in lt:
out[k].append(v)
dict.setdefault
:
out = {}
for k, v in lt:
out.setdefault(k, []).append(v)
Example:
In [11]: lt = [(1, 'a'),(1, 'b'),(2, 'a'),(3, 'b'),(3, 'c')]
In [12]: out = {}
In [13]: for k, v in lt:
...: out.setdefault(k, []).append(v)
...:
In [14]: out
Out[14]: {1: ['a', 'b'], 2: ['a'], 3: ['b', 'c']}
In [15]: out = collections.defaultdict(list)
In [16]: for k, v in lt:
...: out[k].append(v)
...:
...:
In [17]: out
Out[17]: defaultdict(list, {1: ['a', 'b'], 2: ['a'], 3: ['b', 'c']})