2

I have dict with structure like this:

my_dict[object_1] = {'alfa': '1', 'beta': '2', 'etc': '3'}
my_dict[object_2] = {'alfa': '5', 'beta': '9', 'etc': '1'}
my_dict[object_3] = {'alfa': '7', 'beta': '3', 'etc': '3'}
my_dict[object_4] = {'alfa': '3', 'beta': 'a', 'etc': '2'}

And I want sort this on key 'alfa', I want to get this:

my_dict[object_1] = {'alfa': '1', 'beta': '2', 'etc': '3'}
my_dict[object_4] = {'alfa': '3', 'beta': 'a', 'etc': '2'}
my_dict[object_2] = {'alfa': '5', 'beta': '9', 'etc': '1'}
my_dict[object_3] = {'alfa': '7', 'beta': '3', 'etc': '3'}

How to do it?

Nips
  • 13,162
  • 23
  • 65
  • 103

1 Answers1

5

You can iterate over sorted items of dictionary As soon as items() returns list of tuples with key-value One can get it first and sort it then.

>>> a = {1: {'alfa': '1', 'beta': '2', 'etc': '3'},
         2: {'alfa': '5', 'beta': '9', 'etc': '1'},
         3: {'alfa': '7', 'beta': '3', 'etc': '3'}, 
         4: {'alfa': '3', 'beta': 'a', 'etc': '2'}}
>>> for k,v in sorted(a.items(), key=lambda x: x[1]['alfa']):
        print (k, v)
(1, {'etc': '3', 'beta': '2', 'alfa': '1'})
(4, {'etc': '2', 'beta': 'a', 'alfa': '3'})
(2, {'etc': '1', 'beta': '9', 'alfa': '5'})
(3, {'etc': '3', 'beta': '3', 'alfa': '7'})
oleg
  • 4,082
  • 16
  • 16