0Nicholas
0Nicholas

Reputation: 409

Sorting the keys of a dictionary based on different values

I have a dictionary:

d = {"A":{"a":1, "b":2, "c":3}, "B":{"a":5, "b":6, "c":7}, "C":{"a":4, "b":6, "c":7}}

I want to sort the keys "A", "B" and "C" in a list, first on the basis of numerical values of "a", then if some tie occurs on the basis of numerical values of "b" and so on.

How can I do it?

Upvotes: 0

Views: 81

Answers (3)

Carlos Afonso
Carlos Afonso

Reputation: 1957

You can use:

sorted(d, key=lambda key:(d[key]['a'], d[key]['b'], d[key]['c']))

And here is a general solution in case you have an arbitrary number of elements in the inner dictionaries:

sorted(d, key=lambda key:[value for value in sorted(d[key].items())])

Upvotes: 3

Gareth Davidson
Gareth Davidson

Reputation: 4917

Make a list of your dictionary like so:

my_list = [(key, value) for item in d.items()]

Then sort the list using whatever criteria you have in mind:

def sort_function(a, b):
   # whatever complicated sort function you like
   return True if a > b else False

my_list.sort(sort_function)

Upvotes: 0

vz0
vz0

Reputation: 32923

>>> d = {"A":{"a":1, "b":2, "c":3}, "B":{"a":5, "b":6, "c":7}, "C":{"a":4, "b":6, "c":7}}
>>> 
>>> d.items()
[('A', {'a': 1, 'c': 3, 'b': 2}), ('C', {'a': 4, 'c': 7, 'b': 6}), ('B', {'a': 5, 'c': 7, 'b': 6})]
>>> sorted(d.items(), key=lambda x: [y[1] for y in sorted(x[1].items())])
[('A', {'a': 1, 'c': 3, 'b': 2}), ('C', {'a': 4, 'c': 7, 'b': 6}), ('B', {'a': 5, 'c': 7, 'b': 6})]

Upvotes: 2

Related Questions