Skranbets
Skranbets

Reputation: 25

Sort an outer Dictionary using Inner dictionary value (Python)

I currently have a dictionary which looks like this:

mydict = {
1: {
    "desc": "lol",
    "completed": False,
    "priority": 2,
    "project": "lpl"

},
12: {
    "desc": "lol",
    "completed": False,
    "priority": 1,
    "project": "lpl"

},
13: {
    "desc": "lol",
    "completed": False,
    "priority": 0,
    "project": "lpl"

}}

I would like to sorted it by the priority, is that possible?

Upvotes: 1

Views: 54

Answers (3)

J. Taylor
J. Taylor

Reputation: 4865

If you want to sort them in ascending order (smallest to largest):

sorted(mydict, key=lambda k: mydict[k]['priority'])

If you would prefer in descending order (largest to smallest)

sorted(mydict, key=lambda k: mydict[k]['priority'], reverse=True)

This will return a list of keys, in sorted order. So for instance to iterate over the example list you gave, in sorted order, you would do:

sorted_keys = sorted(mydict, key=lambda k: mydict[k]['priority'])

for k in sorted_keys:
     do_something_with(mydict[k])

Keep in mind though that this does not modify the original dict.

Upvotes: 2

Avij
Avij

Reputation: 694

In plain python, it can be done as below

mydict = {
    1: {
        "desc": "lol",
        "completed": False,
        "priority": 2,
        "project": "lpl"

    },
    12: {
        "desc": "lol",
        "completed": False,
        "priority": 1,
        "project": "lpl"

    },
    13: {
        "desc": "lol",
        "completed": False,
        "priority": 0,
        "project": "lpl"

    }}


def func(x):
    return mydict[x]['priority']


m = sorted(mydict, key=func)
for item in m:
    print(item, mydict[item])

Will print below o/p -

13 {'desc': 'lol', 'completed': False, 'priority': 0, 'project': 'lpl'}
12 {'desc': 'lol', 'completed': False, 'priority': 1, 'project': 'lpl'}
1 {'desc': 'lol', 'completed': False, 'priority': 2, 'project': 'lpl'}

Upvotes: 0

cullzie
cullzie

Reputation: 2755

Sorted by priority:

sorted(mydict.iteritems(), key=lambda key_value: key_value[1].get('priority'))

If using python 2.7.* upto python 3.5 then you will need to use an OderedDict from collections in order to cast back to a dictionary otherwise you will lose the order.

from collections import OrderedDict
OrderedDict(sorted(mydict.iteritems(), key=lambda key_value: key_value[1].get('priority')))

From python 3.6+ dictionaries are ordered based on the insertion order

Upvotes: 0

Related Questions