pythonlistsortingdictionarysortedlist

Sort all lists of values in dictionary


I have a dictionary, where keys are strings and values are all lists. For example:

dict = {"Fruits": ["banana", "apple", "pear"], "Vegetables": ["carrot", "cabbage", "potato", "brocoli"], "Berries": ["strawberry", "rasberry", "cranberry"], etc}

I need to sort only the lists of values, so the result would be:

dict = {"Fruits": ["apple", "banana", "pear"], "Vegetables": ["brocoli", "cabbage", "carrot", "potato"], "Berries": ["cranberry", "rasberry", "strawberry"], etc}

There might be more than three keys in the dictionary, so the code should consider the entire length of the dictionary and sort all the value lists accordingly. Keys don't need to be sorted, they can stay as they are.

How can I write this code?


Solution

  • Another solution:

    dct = {
        "Fruits": ["banana", "apple", "pear"],
        "Vegetables": ["carrot", "cabbage", "potato", "brocoli"],
        "Berries": ["strawberry", "rasberry", "cranberry"],
    }
    
    for v in dct.values():
        v.sort()
    
    print(dct)
    

    Prints:

    {
        "Fruits": ["apple", "banana", "pear"],
        "Vegetables": ["brocoli", "cabbage", "carrot", "potato"],
        "Berries": ["cranberry", "rasberry", "strawberry"],
    }