【问题标题】:sorting dictionary with list value (python) [duplicate]使用列表值排序字典(python)[重复]
【发布时间】:2021-06-30 05:35:57
【问题描述】:
dict={"a":[1,2,3,12],"b":[5,6,7,8],"c":[9,10,11,4]}

这是我的字典,我想按每个值列表的最后一个索引对dict 进行排序...可以吗? 我的意思是我想按这个数字 4、8、12 对dict 进行排序并打印出来。 所以输出将是:

{'a': [9, 10, 11, 4], 'b': [5, 6, 7, 8], 'c': [1,2,3,12]}

【问题讨论】:

标签: python-3.x dictionary


【解决方案1】:

不应将 Python 变量命名为 dict。我将改为调用字典d

$ python
Python 3.8.6 (default, Jan 27 2021, 15:42:20)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {"a":[1,2,3,12],"b":[5,6,7,8],"c":[9,10,11,4]}

这会产生字典项目的排序列表:

>>> sorted(list(d.items()), key=lambda x: x[1][3])
[('c', [9, 10, 11, 4]), ('b', [5, 6, 7, 8]), ('a', [1, 2, 3, 12])]

现在我们可以得到排序后的字典了:

>>> dict(sorted(list(d.items()), key=lambda x: x[1][3]))
{'c': [9, 10, 11, 4], 'b': [5, 6, 7, 8], 'a': [1, 2, 3, 12]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    相关资源
    最近更新 更多