如何打印按键排序的字典?
How to print dict sorted by keys?
我的用例涉及打印 json。为了帮助易读性,我想打印它按键排序。 dict
就像我的情况一样 json.loads
returns a dict
.
我尝试过的事情:
dict.__str__ = myStrFn
结果是 TypeError: can't set
attributes of built-in/extension type 'dict'
按照myDict
。这不适用于
嵌套字典,因为嵌套字典的类型为 dict
而不是 myDict
.
我在这里有什么选择?我更喜欢让 print(json.loads(json_str))
工作的东西。但会满足于 print(str_func(json.loads(json_str)))
.
如果您有针对我的 json 用例的解决方案,那也很好。但我更喜欢一个通用的答案。我知道 dict
键只需要 hashable
而不是 "comparable" (从某种意义上说,可能没有总顺序),因此绝对通用的解决方案可能是不可能的。但我倾向于相信我们可以为所有有效的 JSON 类型找到解决方案。
我正在使用 python3
print(json.dumps(your_dict, sort_keys=True))
我的用例涉及打印 json。为了帮助易读性,我想打印它按键排序。 dict
就像我的情况一样 json.loads
returns a dict
.
我尝试过的事情:
dict.__str__ = myStrFn
结果是TypeError: can't set attributes of built-in/extension type 'dict'
按照
myDict
。这不适用于 嵌套字典,因为嵌套字典的类型为dict
而不是myDict
.
我在这里有什么选择?我更喜欢让 print(json.loads(json_str))
工作的东西。但会满足于 print(str_func(json.loads(json_str)))
.
如果您有针对我的 json 用例的解决方案,那也很好。但我更喜欢一个通用的答案。我知道 dict
键只需要 hashable
而不是 "comparable" (从某种意义上说,可能没有总顺序),因此绝对通用的解决方案可能是不可能的。但我倾向于相信我们可以为所有有效的 JSON 类型找到解决方案。
我正在使用 python3
print(json.dumps(your_dict, sort_keys=True))