How to sort list inside dict in Python?
Asked Answered
E

2

8

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.

Edgington answered 22/10, 2015 at 3:53 Comment(2)
what method? I am printing out as json in django template output.Edgington
... The sort method.Amide
T
15

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 ---^
Turnover answered 22/10, 2015 at 3:59 Comment(1)
I have upvoted your answer and accepted it. I don't know who else did it.Edgington
K
6

Not sure if you have a typo in your snippets, but here's one way to sort the values of a dictionary, where the values are lists:

>>> d1 = {"B" : ["x", "z", "k"], "A" : ["a", "c", "b"]}
>>> d2 = {x:sorted(d1[x]) for x in d1.keys()}
>>> d2
{'A': ['a', 'b', 'c'], 'B': ['k', 'x', 'z']}
Kepi answered 22/10, 2015 at 3:57 Comment(3)
More specifically, this results in a new dictionary where the value lists are sorted. This may or may not be what is desired.Amide
Well, that would need clarification from the asker, I guess. :|Kepi
@AlexReynolds, your answer kinda helped me. But the other answer was perfect. Thank you for helping me anyways. :D I really appreciate it.Edgington

© 2022 - 2024 — McMap. All rights reserved.