-1

I have dictorinariesliek these (because they are very large, I made an example):

data_dict =
{'entry1': {'key1': 'c', 'key2': 'cc', 'key3': 'ccc'},
 'entry2': {'key1': 'a', 'key2': 'aa', 'key3': 'aaa'},
 'entry3': {'key1': 'b', 'key2': 'bb', 'key3': 'bbb'}}

I now want to sort the entries order in dict by their value of (for exmaple) key2. Like this:

data_dict =
{'entry2': {'key1': 'a', 'key2': 'aa', 'key3': 'aaa'},
 'entry3': {'key1': 'b', 'key2': 'bb', 'key3': 'bbb'},
 'entry1': {'key1': 'c', 'key2': 'cc', 'key3': 'ccc'}}

I tried the following expression. But it fails with an exception:

data_dict = sorted( data_dict.items(), key = lambda item:item[sortKey] )

Maybe you can help me?

k1ngarthur
  • 124
  • 1
  • 12

1 Answers1

1

try this and don't use reserve word like dict:

dct ={'entry1': {'key1': 'c', 'key2': 'cc', 'key3': 'ccc'},'entry2': {'key1': 'a', 'key2': 'aa', 'key3': 'aaa'},'entry3': {'key1': 'b', 'key2': 'bb', 'key3': 'bbb'}}

dct = sorted( dct.items(), key = lambda item:item[1]['key2'] )

dct

output:

[('entry2', {'key1': 'a', 'key2': 'aa', 'key3': 'aaa'}),
 ('entry3', {'key1': 'b', 'key2': 'bb', 'key3': 'bbb'}),
 ('entry1', {'key1': 'c', 'key2': 'cc', 'key3': 'ccc'})]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30