1

I would like to sort a python dictionary by multiple criteria depending on a condition on its values, like:

d = {'27': 'good morning', '14': 'morning', '23': 'good afternoon', '25': 'amazing'}

priority_1 = 'good'
priority_2 = 'morning'
priority_3 = 'afternoon'
new_d = sorted(d.items(), key=lambda c: [(priority_1 and priority_2) in c[1], priority_3 in c[1]])

this gives:

[('25', 'amazing'),
 ('23', 'good afternoon'),
 ('27', 'good morning'),
 ('14', 'morning')]

While I expected it to return:

    [('25', 'amazing'),
     ('23', 'good afternoon'),
     ('14', 'morning'),
     ('27', 'good morning')]

More interestingly, I thought that writing priority_1 and priority_2 in c[1] is no different from priority_2 and priority_1 in c[1], but It turns out I am mistaken, as when I change the order to priority_2 and priority_1 in c[1] I get a different result.

I could not find an answer in the docs regarding the effect of the order of operands when used with logical operators.

5
  • 3
    try this: (priority_1 in c[1]) and (priority_2 in c[1])
    – girdeux
    Commented Jan 7 at 13:53
  • I do not understand your expected result Commented Jan 7 at 13:55
  • 2
    You are using logical and on strings : it's not doing what you think it's doing. Research that.
    – nicomp
    Commented Jan 7 at 13:55
  • Why amazing should be sorted out first, it's not in any of the priority Commented Jan 7 at 13:55
  • @anom907zat: True sorts after False, so items where both conditions are false go in front. Commented Jan 7 at 14:22

1 Answer 1

0

(priority_1 and priority_2) in c[1] probably doesn't do what you think it does. It doesn't check if both exist in c[1]; it first does (priority_1 and priority_2) as its own expression. Doing and on two strings will return an empty string if either of them is empty, or the second of the two otherwise. So it always evaluates to morning. Then it checks if morning exists in c[1].

2
  • 4
    priority_1 and priority_2 evaluates to 'morning', not True. Commented Jan 7 at 13:59
  • Yes of course, you’re right. Updating the answer.
    – SimonL
    Commented Jan 7 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.