python:基于键排序键:值对

标签 python

我有一本字典

    i={106:0.33,107:0.21,98:0.56}

我想根据键对键:值对进行排序。我期望输出如下所示:

    {98:0.56, 106:0.33, 107:0.21}

当我使用这个时:

    od = collections.OrderedDict(sorted(i.items()))
    print(od)

我得到错误的输出:

    [(98,0.56),(106,0.33),(107,0.21)]

任何人都可以帮我提供正确的代码吗?

最佳答案

OrderedDict 会记住您向字典添加项目的顺序,而不是排序顺序。

但是您可以轻松地从常规字典创建排序列表。例如:

>>> list1={106:0.33,107:0.21,98:0.56}
>>> sorted(list1.items())
[(98, 0.56), (106, 0.33), (107, 0.21)]

或者,如果您希望将其放在 OrderedDict 中,只需在排序后应用 OrderedDict:

>>> from collections import OrderedDict
>>> 
>>> list1={106:0.33,107:0.21,98:0.56}
>>> OrderedDict(sorted(list1.items()))
OrderedDict([(98, 0.56), (106, 0.33), (107, 0.21)])

但是常规字典没有排序顺序的概念,因此您无法对字典本身进行排序。

但是,如果您确实想要这种显示,您可以创建自己的类:

>>> from collections import OrderedDict
>>> class MyDict(OrderedDict):
...     def __repr__(self):
...         return '{%s}' % ', '.join(str(x) for x in self.items())
... 
>>> list1={106:0.33,107:0.21,98:0.56}
>>> MyDict(sorted(list1.items()))
{(98, 0.56), (106, 0.33), (107, 0.21)}

关于python:基于键排序键:值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513853/

相关文章:

python - 剪贴板到 .txt 文件或类似的 Python OSX

python - Numpy.unique 行为(扁平化不一致?)

python - 如何将行值转换为 Pandas 中的属性(列)

Python使用迭代将条目从csv文件添加到字典

python - 为什么 Python linecache 影响回溯模块而不是常规回溯?

python - 为什么 django queryset.extra() 抛出 OperationalError : (1242, 'Subquery returns more than 1 row' )?

python - 如何使用 EPD python 让 FEniCS 在 Ubuntu 12.04 中工作?

python - python 中的轨迹相交

python - 整数字段前缀零不显示

python - 我必须安装什么来解决 Could not find any typelib for GtkSource, Cannot import : GtkSourceView, cannot import name GtkSource