python novice
python novice

Reputation: 379

Sorting dictionary list values

i have the following defaultdict

(<tpe 'list'>, {'one' : ['1a','3f','2z'], 'two' : ['6x','9d','2q']})

is there a way such that my values per key will be sorted and have the new defaultdict as:

(<tpe 'list'>, {'one' : ['1a','2z','3f'], 'two' : ['2q','6x','9d']})

Upvotes: 3

Views: 74

Answers (3)

MaThMaX
MaThMaX

Reputation: 2015

Here is my one-liner using dict generator approach:

dict((k,sorted(v)) for k, v in d.items())

Output:

d = {'one': ['1a', '3f', '2z'], 'two': ['6x', '9d', '2q']}
dict((k,sorted(v)) for k, v in d.items())
Out[81]: {'one': ['1a', '2z', '3f'], 'two': ['2q', '6x', '9d']}

Upvotes: 2

pzp
pzp

Reputation: 6607

Iterate through the values of the dictionary and call the sort method on each one.

d = {'one': ['1a', '3f', '2z'], 'two': ['6x', '9d', '2q']}
for v in d.itervalues():
    v.sort()

print d
# OUT: {'two': ['2q', '6x', '9d'], 'one': ['1a', '2z', '3f']}

Upvotes: 0

Rajiv Sharma
Rajiv Sharma

Reputation: 7132

you can sort the dictionary list values like that:

my_dict = {'one': ['1a', '3f', '2z'], 'two': ['6x', '9d', '2q']}
print my_dict
for key, value in my_dict.iteritems():
    my_dict[key] = sorted(value)
print my_dict

Upvotes: 0

Related Questions