【问题标题】: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 文件中的多个键,这些字典包含相同的键但使用 Python 的不同值
【发布时间】:2021-12-29 00:03:49
【问题描述】:

我目前正在尝试编辑一个 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' 键标记为“'NAMES'”,并将所有 'Hight' 键标记为 'HIGHT (ft)'。

我正在使用 Python,这是一个包含 100 个字典的数据集,我正在尝试编辑,因此一次浏览一个字典效率不高。

【问题讨论】:

  • 您确定文件中数据的引用吗?
  • 这只是我输入的一个例子。它不是我正在使用的实际数据,但问题仍然相同

标签: python dictionary key


【解决方案1】:

我假设架构实际上格式正确(引号中的“属性”,使用双引号而不是单引号,列表中对象之间的逗号)。

您可以执行以下操作来重命名字段:

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))

【讨论】:

  • 这非常有用,但我试图更改的不是 2 个而是 8 个不同的键。我是否需要像您的示例中那样检查所有 8 个,还是有更快的方法来做到这一点?
【解决方案2】:

如果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))

【讨论】:

  • 这也有点帮助,但我不仅试图将键更改为大写,而且还将其中一些键完全更改为不同的名称。
  • 您可以将fields_to_upper 替换为包含字段及其应转换为的值的字典,并遍历此字典。
  • 由于您似乎是 SO 新手,我想向您解释一些事情 - 如果您没有在问题中正确解释它,人们不应该猜测您的实际意思。您应该提供尽可能多的上下文。在最初的问题中,您既没有提到名称应该更改为完全不同的值,也没有提到它应该适用于多个字段。
猜你喜欢
  • 2014-04-27
  • 1970-01-01
  • 2020-07-01
  • 2023-03-16
  • 2018-08-02
  • 2015-11-15
  • 1970-01-01
  • 2019-09-18
  • 1970-01-01
相关资源
最近更新 更多