2

How to sort the python multi-level dictionary by it's value ?

test_dict = {'Items1':{'name':'Homer', 'age':39},'Items2':{'name':'Bart', 'age':10},'Items3':{'name':'Json','age':20}}

after sorting by 'age' , it should be

test_dict = {'Items2':{'name':'Bart', 'age':10},'Items3':{'name':'Json','age':20},'Items1':{'name':'Homer', 'age':39}}

My apologies for the inconvenience. Corrected the question.

Jackie
  • 129
  • 17

2 Answers2

4

You can do so with the default libraries and the sorted() method:

from collections import OrderedDict

test_dict = {
    'Items1':{'name':'Homer', 'age':39},
    'Items2':{'name':'Bart', 'age':10},
    'Items3':{'name':'Json','age':20}
}

sorted_dict = OrderedDict()
sorted_keys = sorted(test_dict, key=lambda x: test_dict[x]["age"])     

for key in sorted_keys: 
    sorted_dict[key] = test_dict[key]

print(sorted_dict)

Output:

OrderedDict([('Items2', {'age': 10, 'name': 'Bart'}), ('Items3', {'age': 20, 'name': 'Json'}), ('Items1', {'age': 39, 'name': 'Homer'})])
TrakJohnson
  • 1,755
  • 2
  • 18
  • 31
  • Looks very simple :) , without using any external library. There must be some difference for using pandas !!!, but not sure. When you print sorted_dict , it prints as OrderedDict !!! why ? My doubts might sounds very silly but i'm very new to python. – Jackie Feb 15 '17 at 14:02
  • 1
    As other answers and comments have mentioned, if you need a dict as output, then you must use an ```OrderedDict```, because a normal dict will not keep the order you set it. An ordered dict will behave just like a normal dict, but it will keeps its keys and values' order. – TrakJohnson Feb 15 '17 at 14:05
2

First, note that regular python dictionary is not ordered. For ordering dictionaries, you need to use OrderedDict

To answer your question, you can use the pandas library which is very useful for handling data, by loading your items to pandas, sort them, and export back to an ordered dictionary

import pandas as pd
df = pd.DataFrame(test_dict)
result = df.sort_values(by='age', axis=1, ascending=True).apply(OrderedDict)

Resulting with

Items2     {u'age': 10, u'name': u'Bart'}
Items3     {u'age': 20, u'name': u'Json'}
Items1    {u'age': 39, u'name': u'Homer'}
Yuval Atzmon
  • 5,645
  • 3
  • 41
  • 74
  • 1
    No need for pandas here. You can simply use sorted : test_dict['Items'] = sorted(test_dict['Items'], key=lambda x:x['age']) – Guillaume A. Feb 15 '17 at 11:49
  • @user2476373: My apologies for the inconvenience. Corrected the question. – Jackie Feb 15 '17 at 13:06
  • @GuillaumeA.: My apologies for the inconvenience. Corrected the question. – Jackie Feb 15 '17 at 13:07
  • @Jackie, I updated the answer following your correction – Yuval Atzmon Feb 15 '17 at 13:27
  • @user2476373 : Thank u. I was not aware of this pandas, but got something new to learn 'Python Data Analysis Library'. – Jackie Feb 15 '17 at 13:55
  • @ user2476373 : What's the difference between using pandas and without using pandas (below answer of Trak Johnson) ? – Jackie Feb 15 '17 at 14:03
  • Both alternatives are good. I like the pandas library because it enables you to work on chunks of data and do complex manipulations in an easy way, that is very intuitive. – Yuval Atzmon Feb 15 '17 at 14:12
  • 1
    I agree with @user2476373, however in some cases where you don't have access to external libraries its a good idea to know how to use ```sorted()``` and especially the ```key``` argument. – TrakJohnson Feb 15 '17 at 14:17