Python中如何排序list中的列表? [英] How to sort list inside dict in Python?

查看:199
本文介绍了Python中如何排序list中的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按字母顺序对列表中的列表进行排序,但无法做到这一点。我的列表是

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

我想做的是,

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

我的代码是

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

b = dict()

为key,a.items()中的值:
b [str(key).replace(' ','')] = value

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

for x在ab中:
ab [x] .sort

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

我得到的输出是

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

任何人都可以告诉我我的错误在哪里?我正在打印出django模板json输出。

解决方案

您实际上并没有调用 sort 方法。只需指定 sort 将返回对 sort 方法的引用,该方法甚至不会在您的情况下任何地方分配。为了实际调用它,您应该在ab中添加括号:

  for ab:
ab [x]。 sort()
#这里--- ^


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.

解决方案

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 ---^

这篇关于Python中如何排序list中的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆