Sort all lists of values in dictionary

Question:

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?

Answers:

try:

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

#1. using loop: (modify dictionary in place)
for k,v in d.items():
    d[k] = sorted(v)

#2. using dictionary comprehensions: (will create new dictionary)
d1 = {k: sorted(v) for k, v in d.items()}

#3. using .update: (modify dictionary in place)
d.update((k, sorted(v)) for k,v in d.items())

print(d)
{'Fruits': ['apple', 'banana', 'pear'],
 'Vegetables': ['brocoli', 'cabbage', 'carrot', 'potato'],
 'Berries': ['cranberry', 'rasberry', 'strawberry']}

Answered By: khaled koubaa

You can go with a comprehension like this:

input_data = {"Fruits": ["banana", "apple", "pear"], "Vegetables": ["carrot", "cabbage", "potato", "brocoli"], "Berries": ["strawberry", "rasberry", "cranberry"]}
sorted_data = {key: sorted(value) for key, value in input_data.items()}

PS: try to not name your variables like build-in names (like dict)

Answered By: Lukas

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"],
}
Answered By: Andrej Kesely