python - 如果值为列表,则按字典中的值排序

标签 python python-3.x

我知道字典是不可排序的,也就是说,我想要字典的表示形式是根据列表的值排序的。示例:

some_dict= {
    "a": [0, 0, 0, 0, 0],
    "b": [1400, 50, 30, 18, 0],
    "c": [800, 30, 14, 14, 0],
    "d": [5000, 100, 30, 50, .1],
    "for fun": [140000, 1400, 140, 140, .42]
}

我想按每个列表中的第一项排序。

我试过类似的方法:

sorted(some_dict.items(), key = lambda for x in some_dict: some_dict[x][0])

但是我得到了无效的语法。

提前致谢。

最佳答案

你走在正确的轨道上,但你不能在 lambda 中放置 for 循环(因此出现错误):

>>> sorted(some_dict.items(), key=lambda x: x[1][0])
[('a', [0, 0, 0, 0, 0]), ('c', [800, 30, 14, 14, 0]), ('b', [1400, 50, 30, 18, 0]), ('d', [5000, 100, 30, 50, 0.1]), ('for fun', [140000, 1400, 140, 140, 0.42])]

如果你想在字典中保留这个顺序,你可以使用collections.OrderedDict :

>>> from collections import OrderedDict
>>> mydict = OrderedDict(sorted(some_dict.items(), key=lambda x: x[1][0]))
>>> print(mydict)
OrderedDict([('a', [0, 0, 0, 0, 0]), ('c', [800, 30, 14, 14, 0]), ('b', [1400, 50, 30, 18, 0]), ('d', [5000, 100, 30, 50, 0.1]), ('for fun', [140000, 1400, 140, 140, 0.42])])
>>> print(mydict['a'])
[0, 0, 0, 0, 0]

关于python - 如果值为列表,则按字典中的值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17768255/

相关文章:

python - 在 Python/Numpy 中使用单词构建转换矩阵

python - 单击图例 python 散点图中的数据开/关

python - 使用python增加图像中特定像素的亮度

python - 将动态用户输入插入到 text() 框中

javascript - 如何将 unicode 转义序列 URL 转换为 python unicode?

python - 在没有 Iteration 或 find() 的情况下检查列表中的特定项目

python - 在 python 中创建一个简单的数字模式?

正则表达式 Python 在 ( ) 之间拉动

python - 如何绘制 K 均值算法的混淆/相似矩阵

python-3.x - 使用 GRPC Python 客户端时 Clarifai 返回握手错误