【问题标题】:Not sorting keys when creating an dictionary fromkeys从键创建字典时不排序键
【发布时间】:2019-08-13 00:14:11
【问题描述】:

从键创建字典时:

mydict = dict.fromkeys(['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11'], np.linspace(-1.2, -0.8, num=5))

我得到了预先排序的键:

'c1': array([-1.2, -1.1, -1. , -0.9, -0.8]),
'c10': array([-1.2, -1.1, -1. , -0.9, -0.8]),
'c11': array([-1.2, -1.1, -1. , -0.9, -0.8]),
'c2': array([-1.2, -1.1, -1. , -0.9, -0.8]),
...

如何按照列表中给定的顺序获取包含条目的字典?

【问题讨论】:

  • 你用的是什么版本的python?

标签: python


【解决方案1】:

问题是典型的python dict 不允许您定义其键的顺序。如果你想这样做,你需要使用OrderedDict。必要的会很小。

from collections import OrderedDict
mydict = OrderedDict.fromkeys(['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11'], np.linspace(-1.2, -0.8, num=5))

我还可以强烈建议查看 https://stackoverflow.com/a/39537308/10833207,以更好地解释 dict 键排序在 python 中的工作原理,尤其是对于它的不同版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-07
    • 2021-11-27
    • 2011-06-17
    • 2021-03-28
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多