【发布时间】:2020-10-23 11:43:46
【问题描述】:
我有以下清单:
import json
import pprint
scoring_dictionary=[{'IMEI': '867',
'Timestamp': '2020-07-02 13-29-24',
'RAG': 'G',
'Probability': 0.12},
{'IMEI': '430',
'Timestamp': '2020-07-02 13-29-24',
'RAG': 'G',
'Probability': 0.12},
{'IMEI': '658',
'Timestamp': '2020-07-02 13-29-24',
'RAG': 'G',
'Probability': 0.12},
{'IMEI': '157',
'Timestamp': '2020-07-02 13-29-24',
'RAG': 'G',
'Probability': 0.12},
{'IMEI': '521',
'Timestamp': '2020-07-02 13-29-24',
'RAG': 'G',
'Probability': 0.12}]
我想在单元格的标准输出中漂亮地打印它。 在网上类似的问题上看到了这段代码,
print("The list of dictionaries per scored asset id: {0}".format(json.dumps(json.loads(scoring_dictionary), indent=4)))
但输出仍然很糟糕
"The list of dictionaries per scored asset id: [{'IMEI': '867', 'Timestamp': '2020-07-02 13-29-24', 'RAG': 'G', 'Probability': 0.12}, {'IMEI': '430', 'Timestamp': '2020-07-02 13-29-24', 'RAG': 'G', 'Probability': 0.12}...]" # a straight text of string without intends
除了字典列表之外,我还想漂亮地打印一个看起来像这样的字典:
{'failed_devices': ['334', '897', '485'], 'partially_succeeded_devices': ['867', '430', '658', '157', '521'], 'total_failures': 705, 'total_partially_succeeded': 268, 'total_succeeded': 26, 'total': 999, 'timestamp': '2020-07-02 13-29-24', 'failures_threshold': 0.1, 'failed_percentage_out_of_total': 0.7057057057057057}
我想以与上面的字典列表完全相同的方式漂亮地打印它。
[更新] 这比 pprint 效果更好。感谢所有答案。感谢您的关注。
print("The list of sotred metrics depicting the complete batch scoring execution: {0}".format(json.dumps(scoring_dictionary, indent=2)))
提前感谢您的帮助。
【问题讨论】:
-
@CoryKramer 这是我看到的一篇帖子,但我的输出完全相同。我会重试,但我认为不会有任何改变
-
这不是 json.dumps 的输出,因为 JSON 必须使用双引号,而不是单引号。您为 print() 显示的代码与您显示的输出不匹配。您也没有格式插入字符串所必需的“{}”
-
试试pprint。在本例中为
from pprint import print; print(lst),其中 lst 是列表。 -
[{'IMEI': '867',不是有效的 JSON。您的代码与输出不匹配。
标签: python json list dictionary pretty-print