在抓取了一些元素后,我生成了幾個 json 檔案。每個檔案的結構如下:
我們.json
{'Pres': 'Biden', 'Vice': 'Harris', 'Secretary': 'Blinken'}
英國.json
{'1st Min': 'Johnson', 'Queen':'Elizabeth', 'Prince': 'Charles'}
我想知道如何編輯 json 檔案中每個字典的結構以獲得如下輸出:
[
{"title": "Pres",
"name": "Biden"}
,
{"title": "Vice",
"name": "Harris"}
,
{"title": "Secretary",
"name": "Blinken"}
]
就我能想到的方法而言(我是初學者,只學習了幾個星期)我首先需要運行一個回圈來打開每個檔案,然后我應該生成一個字典串列,最后修改字典來改變結構。這就是我無法正常作業的原因,因為它始終使用相同的鍵覆寫。
import os
import json
list_of_dicts = []
for filename in os.listdir("DOCS/Countries Data"):
with open(os.path.join("DOCS/Countries Data", filename), 'r', encoding='utf-8') as f:
text = f.read()
country_json = json.loads(text)
list_of_dicts.append(country_json)
for country in list_of_dicts:
newdict = country
lastdict = {}
for key in newdict:
lastdict = {'Title': key}
for value in newdict.values():
lastdict['Name'] = value
print(lastdict)
如果您還可以向我展示如何為每個條目生成 ID 號碼,則額外獎勵。非常感謝
uj5u.com熱心網友回復:
這看起來像是list 理解任務,我會按照以下方式進行
import json
us = '{"Pres": "Biden", "Vice": "Harris", "Secretary": "Blinken"}'
data = json.loads(us)
us2 = [{"title":k,"name":v} for k,v in data.items()]
us2json = json.dumps(us2)
print(us2json)
輸出
[{"title": "Pres", "name": "Biden"}, {"title": "Vice", "name": "Harris"}, {"title": "Secretary", "name": "Blinken"}]
data是dict,.items()提供鍵值對,我將其解壓縮到k和v(請參閱元組解包)。
uj5u.com熱心網友回復:
您可以通過撰寫如下所示的簡單函式輕松完成此操作
import uuid
def format_dict(data: dict):
return [dict(title=title, name=name, id=str(uuid.uuid4())) for title, name in data.items()]
您可以在其中將專案拆分為不同的物件,并使用uuid.
完整代碼可以這樣修改
import uuid
import os
import json
def format_dict(data: dict):
return [dict(title=title, name=name, id=str(uuid.uuid4())) for title, name in data.items()]
list_of_dicts = []
for filename in os.listdir("DOCS/Countries Data"):
with open(os.path.join("DOCS/Countries Data", filename), 'r', encoding='utf-8') as f:
country_json = json.load(f)
list_of_dicts.append(format_dict(country_json))
# list_of_dicts contains all file contents
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364166.html
上一篇:變數未在C 中的范圍錯誤中宣告?
