Python 如何根据需要打印词典输出
我一直在尝试以所需的格式打印字典输出,但python以某种方式按其顺序打印Python 如何根据需要打印词典输出,python,Python,我一直在尝试以所需的格式打印字典输出,但python以某种方式按其顺序打印 identifiers = { "id" : "8888", "identifier" :"7777", } for i in range(1, 2): identifiers['id'] = "{}".format(i) print str(identifiers).replace("'","\"") 我的代码输出: {"identifier": "7777", "id":
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字典没有固定的顺序——即使您以特定的顺序定义了字典,这个顺序也不会存储(或记住)在任何地方。如果要维护字典顺序,可以使用
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字典完全相同,只是记住了插入(或要插入)键值对的顺序。更新字典中的值不会影响键值对的顺序。从本质上讲,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字典完全相同,只是记住了插入(或要插入)键值对的顺序。更新字典中的值不会影响键值对的顺序。字典是无序的,因此添加键的顺序不一定反映您给它们的顺序。如果您关心顺序,请检查以下内容:字典是无序的,因此添加键的顺序不一定反映您给它们的顺序。如果您关心顺序,请检查以下内容:启动python 3.6字典也是按插入顺序的:。启动python 3.6字典也是按插入顺序的:。