Home > Net >  Sorting a dictionary if values be dictionary
Sorting a dictionary if values be dictionary

Time:07-11

I want to sort first by values in small dictionary which is is one big dictionary. Also after that they should be sort by first key in the main dictionary (both should be in descending order). Also if both fails they should be sort out by input order. I wrote the main logic, but I cant get the sort properly. I know it should be used sorted() and lambda but cant get it work. P.S. I dont want to use some functions from collections module.

The result is of the code is:

{'Red': {'Peter': 2000}, 'Blue': {'Teodor': 1000}, 'Green': {'George': 1000}, 'Yellow': {'Simon': 4500}, 'Simon': {'Dopey': 1000}}

I am trying to order them and it should be like this:

(Yellow) Simon <-> 4500

(Red) Peter <-> 2000

(Blue) Teodor <-> 1000

(Green) George <-> 1000

(Simon) Dopey <-> 1000

CodePudding user response:

You can use sorted() on items().

dct = {'Red': {'Peter': 2000}, 'Blue': {'Teodor': 1000}, 'Green': {'George': 1000}, 'Yellow': {'Simon': 4500}, 'Simon': {'Dopey': 1000}}

res = dict(sorted(dct.items(), 
                  key=lambda item: list(item[1].values())[0], 
# --------------------------------------^^^^^^^ -> {'Peter': 2000}, {'Teodor': 1000}, ....
# --------------------------------------------------^^^^^^^^^^^^^^.values() -> 2000, 1000, ...
                  reverse=True))
print(res)

Output:

{'Yellow': {'Simon': 4500}, 'Red': {'Peter': 2000}, 'Blue': {'Teodor': 1000}, 'Green': {'George': 1000}, 'Simon': {'Dopey': 1000}}
  • Related