How to sort a list inside a dict in Python?

I am trying to sort a list inside a dict in alphabetical order, but cannot do this. My list

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

What i want to do

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

my codes

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 conclusion that I get

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

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

+4
source share
2 answers

In fact, you are not calling the method sort. Just an indication sortwill return a reference to a method sortthat is not even assigned anywhere in your case. To actually name it, you must add brackets:

for x in ab:
    ab[x].sort()
    # Here ---^
+4
source

, , , :

>>> 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']}
+3

Source: https://habr.com/ru/post/1612675/


All Articles