How to sort list inside dict in Python?

走远了吗. 提交于 2019-12-01 17:30:29

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

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']}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!