python - 普通字典和 OrderedDictonary 的语法差异

标签 python python-2.7 dictionary ordereddictionary

打印普通字典的语法是

{'a': 1, 'c': 3, 'b': 2}

鉴于

打印 OrderedDict 的语法是

OrderedDict([('a', 1), ('b', 2), ('c', 3)])

有什么方法可以以普通字典的方式打印/返回 OrderedDict 吗?

最佳答案

在您自己的 OrderedDict 类中使用自定义 __str__ 方法;在自定义方法中,您可以构建您想要的字符串:

from collections import OrderedDict

class MyOrderedDict(OrderedDict):
   def __str__(self):
      return "{%s}" % ", ".join([repr(k)+": "+str(v) for k, v in self.iteritems()])

d = MyOrderedDict([('a', 1), ('b', 2), ('c', 3)])

关于python - 普通字典和 OrderedDictonary 的语法差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40956099/

相关文章:

C# 6.0 列表出现语法错误, ' , '

python - 计算 Pandas 日期时间列的累计持续时间

python - 在 Python 中绘制回归线、置信区间和预测区间

python-2.7 - 文本聚类和主题提取

替换字典键和/或值的 Pythonic 方法

scala - 反转 Scala 中的嵌套 Map

python - 为什么我的折线图没有显示在 GUI 上

python - gunicorn:开始:作业无法启动

python - 一行 for 循环并修改对象

python - Flask-Dance错误: Scope has changed