简体   繁体   English

如何在Python中对dict中的列表进行排序?

[英]How to sort list inside dict in Python?

I am trying to sort list inside of dict alphabetically but not able to do it. 我试图按字母顺序对dict中的列表进行排序但不能这样做。 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. 我在django模板json输出中打印出来。

You aren't actually calling the sort method. 你实际上并没有调用sort方法。 Just specifying sort will return a reference to the sort method, which isn't even assigned anywhere in your case. 只是指定sort将返回对sort方法的引用,在您的情况下甚至不会在任何地方分配。 In order to actually call it, you should add parenthesis: 为了实际调用它,你应该添加括号:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM