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.
(priority_1 in c[1]) and (priority_2 in c[1])
True
sorts afterFalse
, so items where both conditions are false go in front.