Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list inside dict in Python?

I am trying to sort list inside of dict alphabetically but not able to do it. My list is

{"B" : ["x", "z", "k"], "A" : ["a", "c", "b"]}

What I want to do is,

{"A" : ["k", "x", "z"], "B" : ["a", "b", "c"]}

my codes are

a = {"B" : ["x", "z", "k"], "A" : ["a", "c", "b"]}

b = dict()

for key, value in a.items():
     b[str(key).replace('"','')] = value

ab = OrderedDict(sorted(b.items(), key=lambda t: t[0]))

for x in ab:
    ab[x].sort

return HttpResponse(json.dumps(ab), content_type="application/json")

the output I am getting is

{ "A" : ["a", "c", "b"], "B" : ["x", "z", "k"]}

can anyone tell me where is my mistake? I am printing out in django template json output.

like image 922
Django Learner Avatar asked Oct 22 '15 03:10

Django Learner


1 Answers

You aren't actually calling the sort method. Just specifying sort will return a reference to the sort method, which isn't even assigned anywhere in your case. In order to actually call it, you should add parenthesis:

for x in ab:
    ab[x].sort()
    # Here ---^
like image 106
Mureinik Avatar answered Sep 21 '22 14:09

Mureinik