Home > Software engineering >  How to sort nested dictionary by values in python
How to sort nested dictionary by values in python

Time:03-03

PROBLEM

I have a dictionary and it is nested i want to sort it using vlaues. There are many solution out there for the same question but I couldnt find one solution that satisfies my sorting condition

CONDITION

I want to sort thee dict in descending order of the given likes in the dict

Dict

dict = {actor_name: {movie_name: likes}

eg:- {'gal gadot': {'red notice': 1000}, 'tom holland': {'spiderman-nwh': 3000}}

output should be:- {'tom holland': {'spiderman-nwh': 3000}, 'gal gadot': {'red notice': 1000}}

CodePudding user response:

I suggest improving your data structure first. As an example you could use a list of dictionaries list[dict].

This would help you later, if you expand your structure.

Try this structure:

data = [
    {
        "actor": "gal gadot",
        "movies": {
            "name": "red notice",
            "likes": 1000,
        },
    },
    {
        "actor": "tom holland",
        "movies": {
            "name": "spiderman-nwh",
            "likes": 3000,
        },
    },
]

Using that structure, you can sort your data like this:

# Least likes first
least_likes_sorted = = sorted(data, key=lambda x: x["movies"]["likes"])

# Most likes first
most_likes_sorted = sorted(data, key=lambda x: x["movies"]["likes"], reverse=True)

CodePudding user response:

You could build a list of tuples where each element is (likes, movie, actor).

Then sort the list in reverse.

Then reconstruct your dictionary.

Like this:

data = {'gal gadot': {'red notice': 1000}, 'tom holland': {'spiderman-nwh': 3000}}
lot = []
for k, v in data.items():
    k_, v_ = next(iter(v.items()))
    lot.append((v_, k_, k))
newdata = {a : {b: c} for c, b, a in sorted(lot, reverse=True)}
print(newdata)

Output:

{'tom holland': {'spiderman-nwh': 3000}, 'gal gadot': {'red notice': 1000}}
  • Related