user1830011
user1830011

Reputation: 185

sort a list alphabetically in a dictionary

I've got following dictionary:

#original
random_dict={'list1': ['b', 'a', 'c'], 'list2': ['f', 'a', 'e'], 'list3': ['c', 'b', 'a']}

how do you sort the lists alphabetically in random_dict to get this:

#after sorting
sorted_dict={'list1': ['a', 'b', 'c'], 'list2': ['a', 'e', 'f'], 'list3': ['a', 'b', 'c']}

Upvotes: 0

Views: 430

Answers (2)

raton
raton

Reputation: 428

python 3.2

r={'list1': ['b', 'a', 'c'], 'list2': ['f', 'a', 'e'], 'list3': ['c', 'b', 'a']}

for i,v in r.items(): r[i]=sorted(v)

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121714

Just call .sort() on each value:

for val in random_dict.values():
    val.sort()

This changes random_dict in-place. If you need a copy, use a dict comprehension instead:

sorted_dict = {k: sorted(v) for k, v in random_dict.iteritems()}

On python 3, replace .iteritems() with .items().

Upvotes: 11

Related Questions