0

I have nested dictionary like this :

dic = {
    1:
    {
        'name': 'alice',
        'point': 10
    },
    2:
    {
        'name': 'john',
        'point': 12
    }
    3:
    {
        'name': 'mike',
        'point': 8
    }
    4:
    {
        'name' : 'rose',
        'point': 16
    }
    5:
    {
        'name': 'ben',
        'point': 5
    }
}

In my case, i need to sort descending that dictionary based on the values of key 'point' in the second level.. So the result will be like this:

{
    4:
    {
        'name' : 'rose',
        'point': 16
    },
    2:
    {
        'name': 'john',
        'point': 12
    },
    1:
    {
        'name': 'alice',
        'point': 10
    },
    3:
    {
        'name': 'mike',
        'point': 8
    },
    5:
    {
        'name': 'ben',
        'point': 5
    }
}

Is there any way to do that? Thanks..

Faizalprbw
  • 529
  • 1
  • 6
  • 17

2 Answers2

1

As others have mentioned, in dictionary form you cannot sort these items. However, here is a solution that may work depending on your needs, converting to key,value tuples and then sorting by points (which is implied by your output but not explicitly stated).

d = {
    4:
    {
        'name' : 'rose',
        'point': 16
    },
    2:
    {
        'name': 'john',
        'point': 12
    },
    1:
    {
        'name': 'alice',
        'point': 10
    },
    3:
    {
        'name': 'mike',
        'point': 8
    },
    5:
    {
        'name': 'ben',
        'point': 5
    }
}

d_sorted = sorted(d.items(), key = lambda x: x[1]['point'],reverse=True)
print(d_sorted)
Solaxun
  • 2,732
  • 1
  • 22
  • 41
0

No, you cannot sort "that dictionary". Dictionaries are orderless. However, you can use a nested list or other things people suggested in the comments. For ordered dictionaries, I suggest you look at this.

whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44