![](/img/trans.png)
[英]How can I add the values of the same keys in different dictionaries in python?
[英]How can I change multiple keys in a JSON file that has multiple dictionaries which incorporate the same keys but different values with Python
我目前正在嘗試編輯一個 JSON 文件,該文件具有多個列出的字典,這些字典包含相同的鍵但不同的值。 我想更改文件中每個字典中的特定鍵(相同的鍵)。 我怎樣才能做到這一點?
例如:
“JSON_FILE”[
{"type" : "person", 'attributes" : { "Name" : "Jack, "Age" : 24, "Hight" : 6.2}}
{"type" : "person", "attributes" : { "Name" : "Brent", "Age" : 15, "Hight" : 5.6}}
{"type" : "person", "attributes" : { "Name" : "Matt", "Age" : 30, "Hight" : 4.9}} ]
我想將所有“名稱”鍵更改為“'NAME'”,並將所有“Hight”鍵更改為“HIGHT”。
我正在使用 Python ,這是我試圖編輯的 100 個字典的數據集,因此一次瀏覽一個字典效率不高。
我假設架構實際上是格式正確的(引號中的“屬性”,使用雙引號而不是單引號,列表中對象之間的逗號)。
您可以執行以下操作來重命名字段:
import json
data = json.load(open('your_file_name.json', 'r'))
for data_entry in data:
# Add new 'NAME' field, then delete old 'Name' field.
data_entry['attributes']['NAME'] = data_entry['attributes']['Name']
del data_entry['attributes']['Name']
# Add new 'HIGHT' (sic) field, then delete old 'Hight' field.
data_entry['attributes']['HIGHT'] = data_entry['attributes']['Hight']
del data_entry['attributes']['Hight']
with open('your_file_name.json', 'w') as output_file:
output_file.write(json.dumps(data))
如果您在大寫attributes
下有多個鍵,則可以執行以下操作:
import json
file_path = "path/to/file"
fields_to_upper = ["Name", "Hight", "Age"]
with open(file_path, "r") as f:
data = json.load(f)
for row in data:
for field in fields_to_upper:
row["attributes"][field.upper()] = row["attributes"].pop(field)
with open(file_path, "w") as f:
f.write(json.dumps(data))
如果要將attributes
下的所有鍵都大寫,請嘗試:
with open(file_path, "r") as f:
data = json.load(f)
for row in data:
for key in row["attributes"].keys():
row["attributes"][key.upper()] = row["attributes"].pop(key)
with open(file_path, "w") as f:
f.write(json.dumps(data))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.