Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: map a list of tuples onto the keys of a dictionary

Given the following list of tuples:

l=[((459301.5857207412, 443923.4365563169),
   (458772.4179957388, 446370.8372844439))]

And the following dictionary:

mydict={0: (459301.5857207412, 443923.4365563169),
        25: (458772.4179957388, 446370.8372844439)}

How could I create a new list where the tuple contains the key in mydict associated with the values of the tuple itself?

The result would be, given the two examples above:

mapped=[(0,25)]
like image 563
FaCoffee Avatar asked Dec 14 '25 21:12

FaCoffee


1 Answers

If

l=[((459301.5857207412, 443923.4365563169),
   (458772.4179957388, 446370.8372844439))]

mydict={0: (459301.5857207412, 443923.4365563169),
        25: (458772.4179957388, 446370.8372844439)}

I suppose I could generalize your simple case with this oneliner:

[tuple(k for k,v in mydict.items() if v in sl) for sl in l]

result:

[(0, 25)]

Note: for better performance, it would be better to pre-process l to create sets inside like this so lookup with in is faster (tuples are immutable/hashable, so let's take advantage of it):

l = [set(x) for x in l]
like image 177
Jean-François Fabre Avatar answered Dec 16 '25 09:12

Jean-François Fabre