Search code examples
pythonsortingdictionarynestedsubdirectory

Nested dictionary sorting by values in sub dictionary and then length of subdictionary


As a newbie I'm struggling with the sorting of a nested dictionary. Lets say i have these two nested dictionaries as examples:

Example 1:

{'Red': {'Pesho': 2000}, 'Blue': {'Tosho': 1000}, 'Green': {'Gosho': 1000}, 'Yellow': {'Sasho': 4500}, 'Stamat': {'Prakasho': 1000}}

Example 2:

{'Red': {'Pesho': 10000}, 'Blue': {'Pesho': 10000, 'Gosho': 10000}}

Now I need to sort the players by points in descending order and then by total number of players within each team/color again in descending order. The print output should look like this:

For example 1:
(Yellow) Sasho <-> 4500
(Red) Pesho <-> 2000
(Blue) Tosho <-> 1000
(Green) Gosho <-> 1000
(Stamat) Prakasho <-> 1000

For example 2:
(Blue) Pesho <-> 10000
(Blue) Gosho <-> 10000
(Red) Pesho <-> 10000

I imagine it can be done with sorted() using lambdas but cant warp my head around the exact syntax. Will be very grateful for any tips.


Solution

  • I would first pass through an intermediate representation to associate the size the group the element belongs to the element in order to use it in the sorting.

    >>> l2 = [(k,el,d[k][el],len(v)) for k,v in d.items() for el in v]
    >>> l2
    [('Red', 'Pesho', 10000, 1), ('Blue', 'Pesho', 10000, 2), ('Blue', 'Gosho', 10000, 2)]
    

    and then sort with a lambda function in which the 2 comparison terms (score, size of group) are used.

    >>> sorted(l2, key=lambda x:(int(x[2]),x[3]),reverse=True)
    [('Blue', 'Pesho', 10000, 2), ('Blue', 'Gosho', 10000, 2), ('Red', 'Pesho', 10000, 1)]