Search code examples
pythonpython-3.9

How to sort a list of nested dictionaries based on a deeply nested key?


I have a list that looks like this:

ls = [
    {
        "max_supply": None,
        "platform": None,
        "quote": {
            "USD": {
                "fully_diluted_market_cap": 464800388135.72,
                "last_updated": "2021-10-20T13:37:02.000Z",
                "market_cap": 464800388135.7246,
                "price": 3938.871641392752,
                "volume_24h": 15411634916.820467,
                "volume_change_24h": -3.4909
            }
        }
    },
    {
        "max_supply": None,
        "platform": None,
        "quote": {
            "USD": {
                "fully_diluted_market_cap": 58764548678.52,
                "last_updated": "2021-10-20T13:37:03.000Z",
                "market_cap": 58764548678.52,
                "price": 4784.77,
                "volume_24h": 189992412916.647,
                "volume_change_24h": 85.422
            }
        }
    },
]

How do I order the given list by each market_cap value that is located in the quote and USD keys?

I have found some solutions but they are only referring to sort by the first-level dictionary keys and values, however I have not been able to find any solutions for sorting by the keys and values in a dictionary two-level deep. in the given list.


Solution

  • You can pass a lambda function as the key argument for the built-in sorted function:

    ls = [
        {
            "max_supply": None,
            "platform": None,
            "quote": {
                "USD": {
                    "fully_diluted_market_cap": 464800388135.72,
                    "last_updated": "2021-10-20T13:37:02.000Z",
                    "market_cap": 464800388135.7246,
                    "price": 3938.871641392752,
                    "volume_24h": 15411634916.820467,
                    "volume_change_24h": -3.4909
                }
            }
        },
        {
            "max_supply": None,
            "platform": None,
            "quote": {
                "USD": {
                    "fully_diluted_market_cap": 58764548678.52,
                    "last_updated": "2021-10-20T13:37:03.000Z",
                    "market_cap": 58764548678.52,
                    "price": 4784.77,
                    "volume_24h": 189992412916.647,
                    "volume_change_24h": 85.422
                }
            }
        },
    ]
    sorted_ls = sorted(ls, key=lambda obj: obj["quote"]["USD"]["market_cap"])
    

    Alternatively, you can use the .sort() method if you want to edit the list in-place.