I have a list of tuples as shown:
lt = [(1,'a'),(1,'b'),(2,'a'),(3,'b'),(3,'c')]
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]
}
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])
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?
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']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With