pythondictionarysortingnested

Sorting a nested dictionary


I want to sort the teams in this dict based on the points and I already followed the advise in this post and the sorted code I wrote doesn't work as I want to.

Here is my dictionary:

{
    'Spain': {
        'wins': 3,
        'loses': 0,
        'draws': 0,
        'goal difference': 4,
        'points': 9
    },
    'Iran': {
        'wins': 0,
        'loses': 3,
        'draws': 0,
        'goal difference': -6,
        'points': 0
    },
    'Portugal': {
        'wins': 2,
        'loses': 1,
        'draws': 0,
        'goal difference': 4,
        'points': 6
    },
    'Morocco': {
        'wins': 1,
        'loses': 2,
        'draws': 0,
        'goal difference': -2,
        'points': 3
    }
}

and the code I used for sorting it:

sorted_dict = OrderedDict(sorted(B_group.items(),key= lambda x:  x[1]["points"] ,reverse=True))

This is the result I get:

Spain  wins:3 , loses:0 , draws:0 , goal difference:4 , points:9
Iran  wins:0 , loses:3 , draws:0 , goal difference:-6 , points:0
Portugal  wins:2 , loses:1 , draws:0 , goal difference:4 , points:6
Morocco  wins:1 , loses:2 , draws:0 , goal difference:-2 , points:3

I want it to put the highest point team first, for example, Spain, Portugal, Morocco, Iran in this list. Is there something wrong with the sorting code I wrote?


Solution

  • You do not need OrderedDict because since Python 3.7 dictionaries maintain the order of insertion. See: Is it good practice to rely on the insertion order of python dicts? - Software Engineering Stack Exchange

    Use proper indexing to access the dictionary values, like so:

    dct = {
        'Spain':    {'wins': 3, 'loses': 0, 'draws': 0, 'goal difference': 4, 'points': 9},
        'Iran':     {'wins': 0, 'loses': 3, 'draws': 0, 'goal difference': -6, 'points': 0},
        'Portugal': {'wins': 2, 'loses': 1, 'draws': 0, 'goal difference': 4, 'points': 6},
        'Morocco':  {'wins': 1, 'loses': 2, 'draws': 0, 'goal difference': -2, 'points': 3}
    }
    
    sorted_dct = {k:dct[k] for k in reversed(sorted(dct, key = lambda x: dct[x]['points']))}
    
    print(sorted_dct)
    # {'Spain': {'wins': 3, 'loses': 0, 'draws': 0, 'goal difference': 4, 'points': 9}, 'Portugal': {'wins': 2, 'loses': 1, 'draws': 0, 'goal difference': 4, 'points': 6}, 'Morocco': {'wins': 1, 'loses': 2, 'draws': 0, 'goal difference': -2, 'points': 3}, 'Iran': {'wins': 0, 'loses': 3, 'draws': 0, 'goal difference': -6, 'points': 0}}