【问题标题】:Python - Creating a dictionary using ListPython - 使用列表创建字典
【发布时间】:2016-01-08 17:52:54
【问题描述】:

我在列表中有以下字符串,并且能够使用列表作为字典中的键并分配默认值''来创建字典。当我打印时,我看到字典是以相反的顺序为列表中的字符串创建的。为什么会发生这种情况以及如何纠正它。是否需要反向语法?

a = ['hello','bye','tc','iam']
created_dict = dict((bl,'') for bl in a)
print created_dict # {'iam': '', 'bye': '', 'hello': '', 'tc': ''}

需要进行哪些更改才能获得以下结果。

expected result : {'hello': '', 'bye': '', 'tc': '', 'iam': ''}

在列表中使用数字时保持顺序

【问题讨论】:

  • 您确定需要订购吗?如果是这样,字典不是您想要的数据结构。列表或链表可能会更好。

标签: python list python-2.7 dictionary


【解决方案1】:

Python 中的常规字典没有键顺序的概念,您需要一个 OrderedDict

from collections import OrderedDict
o = OrderedDict.fromkeys(['hello', 'bye', 'tc', 'iam'], '')                    
repr(o)
OrderedDict([('hello', ''), ('bye', ''), ('tc', ''), ('iam', '')])

【讨论】:

  • “你需要一个 OrderedDict” - 更可能的是,顺序是不必要的,使用 OrderedDict 只会鼓励在面对 dict 修改时尝试维护特定顺序的不必要的麻烦。
猜你喜欢
  • 2023-02-07
  • 2018-09-17
  • 1970-01-01
  • 2020-11-17
  • 2018-04-27
  • 2020-07-22
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
相关资源
最近更新 更多