-1

Went to this question in search for the underlying reason of my mistake, but not sure if I understand why one works and the other doesn't:

Grammatically, for a dictionary where values are tuples:

my_dict = {'Cierra Vega': (6.2, 70), 'Alden Cantrell': (5.9, 65), 
           'Kierra Gentry': (6.0, 68), 'Pierre Cox': (5.8, 66)}

and we wish to filter for key:value pairs where the (a) the first value in the tuple is value[0]> 6 and (b) the second value in the tuple is value[1] > 70,

why does the tuple comparison made to be an element-wise conditional statement succeed

dict(filter(lambda x: (x[1][0], x[1][1]) >= (6, 70), my_dict.items()))
>>>
{'Cierra Vega':(6.2,70)}

but the joint-and comparison fails?

dict(filter(lambda x: ((x[1][0] >= 6) and (x[1][1] >= 70)), my_dict.items()))
>>>
{}
batlike
  • 668
  • 1
  • 7
  • 19
  • What do you mean by "fails"? What does it give you vs what do you expect? – blarg Apr 09 '22 at 14:30
  • The element-wise conditional returns the `key:value` pair `{'Cierra Vega':(6.2,70)}` but the second method returns an empty dictionary `{}` – batlike Apr 09 '22 at 14:31
  • 1
    So your 2nd implementation is the correct one. Note than 70 is not > 70, so the filter result should be empty. – blarg Apr 09 '22 at 14:39

1 Answers1

3

First of all, I am a little confused about "failing" and "succeeding", since no entries of your dictionary actually satisfy your request, so it makes sense that the succeeding case is the latter one, where no results are returned.

And, actually, that makes sense, because tuples are ordered lexicographically, meaning that (a, b) ≥ (c, d) iff a > c or (a == c and b ≥ d). This generalizes to not only couples, but any tuple. So when you are checking for x[1] > (6, 70), it's not at all equivalent to x[1][0] > 6 and x[1][1] > 70, hence the different results.

jthulhu
  • 7,223
  • 2
  • 16
  • 33