如何打印字典输出

2024-04-25 17:27:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试以所需的格式打印字典输出,但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"}

谢谢


Tags: 代码inidformatfor字典顺序格式
1条回答
网友
1楼 · 发布于 2024-04-25 17:27:56

从本质上讲,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字典完全相同,只是记住了插入(或要插入)键值对的顺序。更新字典中的值不会影响键值对的顺序

相关问题 更多 >