Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, list of tuples split into dictionaries

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?

like image 276
PhantomQuest Avatar asked Jul 15 '19 17:07

PhantomQuest


1 Answers

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']}
like image 119
Mark Avatar answered Nov 03 '22 23:11

Mark