0

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?

Floran Gmehlin
  • 824
  • 1
  • 11
  • 34
0Nicholas
  • 389
  • 7
  • 16

3 Answers3

3

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())])
Carlos Afonso
  • 1,927
  • 1
  • 12
  • 22
2
>>> 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})]
vz0
  • 32,345
  • 7
  • 44
  • 77
0

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)
Gareth Davidson
  • 4,857
  • 2
  • 26
  • 45