【问题标题】:how I can change some values of my json file?如何更改我的 json 文件的某些值?
【发布时间】:2021-07-04 15:18:19
【问题描述】:

我有一个 json 文件,它是一个 dic 列表。例如,它的两个元素是:

[{'key': 'chief information security officer',
  'top_transitions': [{'security architect': 5.0},
   {'cyber security manager': 3.0},
   {'information security officer': 3.0}]},
 {'key': 'security auditor',
  'top_transitions': [{'information security analyst': 9.0},
   {'information security officer': 9.0},
   {'it auditor': 6.0}]}]

我需要手动更改top_transitions 的一些值。例如,如何将{'security architect': 5.0} 更改为{'student': 15.0}

【问题讨论】:

  • @MerajAhmed 你能写一个解决方案吗?

标签: python json list dictionary nested


【解决方案1】:

您可以使用此示例将{"security architect": 5.0} 更改为{"student": 15.0}data 从您的 Json 文件中加载):

import json

to_search = {"security architect": 5.0}
to_replace = {"student": 15.0}

for item in data:
    if to_search in item["top_transitions"]:
        item["top_transitions"].remove(to_search)
        item["top_transitions"].append(to_replace)


print(json.dumps(data, indent=4))

打印:

[
    {
        "key": "chief information security officer",
        "top_transitions": [
            {
                "cyber security manager": 3.0
            },
            {
                "information security officer": 3.0
            },
            {
                "student": 15.0
            }
        ]
    },
    {
        "key": "security auditor",
        "top_transitions": [
            {
                "information security analyst": 9.0
            },
            {
                "information security officer": 9.0
            },
            {
                "it auditor": 6.0
            }
        ]
    }
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 2013-03-14
    • 2021-09-02
    • 1970-01-01
    • 2021-10-25
    • 2019-12-10
    • 1970-01-01
    相关资源
    最近更新 更多