Home > OS >  understanding python dictionary sorting
understanding python dictionary sorting

Time:11-03

I am trying to understand dictionary sorting in python and I am stumped by this perplexing issue (I am sure it is something dumb but I am nt able to decode the problem).

So I have this nested dict:

some_dict={'10_key0': {'pass_fail': 1, 'scoring': 94}, '10_key1': {'pass_fail': 0, 'scoring': 38}}

I now try and sort like so:

>>> sorted(some_dict, key=some_dict.get('pass_fail'), reverse=True)
['10_key1', '10_key0']

I dont understand the output - I would have thought it should be:

['10_key0', '10_key1']

Is this not the case? What am I missing?

CodePudding user response:

Your key is off here. some_dict.get('pass_fail') evaluates to None, so your call is essentially equivalent to sorted(some_dict, key=None, reverse=True), which is the same as not passing a key at all. You mean to pass a function that looks at the current element being considered:

key=lambda k:some_dict[k]["pass_fail"]
  • Related