An elegant way to create a dictionary of pairs from a list of tuples?

I defined the tuple this way: (slot, game, bitrate)

and created a list of them called myListOfTuples . This list may contain tuples containing the same gameid .

eg. the list may look like this:

 [ (1, "Solitaire", 1000 ), (2, "Diner Dash", 22322 ), (3, "Solitaire", 0 ), (4, "Super Mario Kart", 854564 ), ... and so on. ] 

From this list I need to create a dictionary of pairs - ( gameid , bitrate ), where the bitrate for this gameid is the first that I came across for this particular gameid in myListOfTuples .

eg. From the above example, the dictionary of pairs will contain only one pair with gameid "Solitaire": ("Solitaire", 1000 ) , because 1000 is the first bitrate found.

NB. I can create a set of unique games with this:

 uniqueGames = set( (e[1] for e in myListOfTuples ) ) 
+7
python
source share
2 answers

For python2.6

 dict(x[1:] for x in reversed(myListOfTuples)) 

If you have Python2.7 or 3.1 you can use katrielalex answer

+10
source share
 { gameId: bitrate for _, gameId, bitrate in reversed( myListOfTuples ) }.items( ) 

(This is a view, not a set. It has operations with similar settings, but if you need a set, translate it into one.)

Are you sure you want to install the set, not the gameId: bitrate dictionary? The latter seems to me to be a more natural data structure for this problem.

+4
source share

All Articles