Python, list of tuples split into dictionaries

Pha*_*est 5 python dictionary tuples list

I have a list of tuples as shown:

lt = [(1,'a'),(1,'b'),(2,'a'),(3,'b'),(3,'c')]
Run Code Online (Sandbox Code Playgroud)

I want to make the numbers keys of a dictionary and have them point to a list. That list then holds all associations in the list of tuples. So in the list above, it would split into a dictionary as:

dict_lt:{
1:[a,b],
2:[a],
3:[b,c]
}
Run Code Online (Sandbox Code Playgroud)

Currently I use the dictionary's flexibility in automatically declaring new keys, which I then force point to an empty list. Then I fill that list accordingly.

dict_lt = {}

for tup in lt:
   dict_lt[tup[0]] = []

for tup in lt:
   dict_lt[tup[0]].append(tup[1])

Run Code Online (Sandbox Code Playgroud)

This works fine, but its a tad slow since it needs to iterate twice over the same list, and it just seems overall redundant. Is there a better way?

Mar*_*yer 5

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)
Run Code Online (Sandbox Code Playgroud)

prints

{1: ['a', 'b'], 2: ['a'], 3: ['b', 'c']}
Run Code Online (Sandbox Code Playgroud)