Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to create a dictionary of pairs, from a list of tuples?

Tags:

python

I have defined a tuple thus: (slot, gameid, bitrate)

and created a list of them called myListOfTuples. In this list might be tuples containing the same gameid.

E.g. the list can look like:

[
   (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 that gameId is the first one that I came across for that particular gameId in myListOfTuples.

E.g. From the above example - the dictionary of pairs would 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 ) )
like image 257
BeeBand Avatar asked Aug 11 '10 11:08

BeeBand


People also ask

How will you create a dictionary using tuples in Python?

To convert a tuple to dictionary in Python, use the dict() method. A dictionary object can be constructed using a dict() function. The dict() function takes a tuple of tuples as an argument and returns the dictionary.

Which dictionary method can we use to access the key-value pairs as a list of tuples?

One of the built-in methods for dictionaries is the . items() methods, which returns a tuple of tuples of the key value pairs found inside the dictionary. We can use this method and pass it into the list() function, in order to generate a list of tuples that contain the key value pairs from our dictionary.

What is the name of the dictionary method that returns a list of pairs represented as tuples?

1) Looping all key-value pairs in a dictionary Python dictionary provides a method called items() that returns an object which contains a list of key-value pairs as tuples in a list.


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's answer

like image 102
John La Rooy Avatar answered Sep 29 '22 09:09

John La Rooy


{ gameId: bitrate for _, gameId, bitrate in reversed( myListOfTuples ) }.items( )

(This is a view, not a set. It has setlike operations, but if you need a set, cast it to one.)

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

like image 34
Katriel Avatar answered Sep 29 '22 07:09

Katriel