[英]How to format a list of nested dictionaries for writing to a file in a human readable form
我有一個大列表,其中列表的每個元素都是字典。 在字典中嵌套了另一個列表,該列表本身包含數百個鍵:值對。 我想將此列表寫入文件,以便:
[
開頭並以]
結尾我希望它看起來像這樣:
[{
"id": "1",
"day": 20190928,
"layer": {
"some_value": "value",
"some_other_value": 2,
"some_value_int": 5,
"imageFormat": "image/png",
},
"elements": [
{
"httpStatusCode": 200,
"requestTime": 1553731321446,
"some_attribute": 143,
"some_binary_value": True,
},
{
"httpStatusCode": 200,
"requestTime": 1553731321446,
"some_attribute": 143,
"some_binary_value": True,
},
# and so on...
我覺得這一定是一項微不足道的任務,但有點迷茫。 這是我嘗試過的:
for item in converted_data:
for key, value in item.items():
if type(value) == dict:
#Implement
pass
elif type(value) == list:
#Implement
pass
else:
outfile.write(" {} : {},\n".format(key, value))
但即使在完成它之前,我也發現這是一種錯誤的方法,會使這個簡單的事情變得非常復雜。 我看過 SO 但沒有找到與我的問題類似的問題。 那么,我該怎么做呢?
我不需要像我建議的那樣成為文件。 我只需要它是人類和機器可讀的。
對於如何解決此問題的任何建議,我將不勝感激。
import json
list_of_dicts # your list
data = json.dumps(list_of_dicts, indent = 4)
# write data to a file...
這將使用 4 個空格進行縮進,如果需要,將 4 更改為其他內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.