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"}
谢谢!
解决方案
从本质上讲,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 字典完全一样,除了记住键值对插入(或插入)的顺序。更新字典中的值不会影响键值对的顺序。
推荐阅读
- javascript - Chrome 一次又一次地触发 OnBlur
- html - 禁用并选中单选按钮不起作用
- math - 不均匀间隔系列的双指数平滑?
- random - 我使用 Oraclize 来获取一个随机数,但是 N 个字节让我感到困惑
- c# - EPPlus 的 Workbook.Add(object) 的变体
- php - Laravel 网站上的分页重定向到主页
- list - CMake - 输入在函数内部不会改变
- javascript - Node.js - performance.now 不是一个函数
- python - 无法加载 Pickle 文件,内存错误
- angularjs - 如何在 ngRepeat 中跳过 $$hashKey