首页 > 解决方案 > 如何根据需要打印字典输出

问题描述

我一直在尝试以所需的格式打印字典输出,但不知怎么的,python 按其顺序打印。

identifiers = {
    "id" : "8888",
    "identifier" :"7777",
    }

for i in range(1, 2):
    identifiers['id'] = "{}".format(i)
    print str(identifiers).replace("'","\"")

我的代码输出:

{"identifier": "7777", "id": "1"}

输出要求:

{"id": "1" , "identifier": "7777"}

谢谢!

标签: python

解决方案


从本质上讲,python 字典没有固定的顺序——即使你已经按照特定的顺序定义了字典,这个顺序也不会存储(或记住)任何地方。如果要维护字典顺序,可以使用OrderedDict

from collections import OrderedDict
identifiers = OrderedDict([
    ("id", "8888"), #1st element is the key and 2nd element is the value associated with that key
    ("identifier", "7777")
    ])

for i in range(1, 2):
    identifiers['id'] = "{}".format(i)

for key, value in identifiers.items(): #simpler method to output dictionary values
    print key, value

这样,您创建的字典的操作与普通的 python 字典完全一样,除了记住键值对插入(或插入)的顺序。更新字典中的值不会影响键值对的顺序。


推荐阅读