【问题标题】:Is there a way in python to add values into a key instead of replacing the existing values in json file?python中有没有办法将值添加到键中而不是替换json文件中的现有值?
【发布时间】:2021-07-04 21:22:24
【问题描述】:

有没有办法将另一个值添加到键中,而不是使用 python 在 json 文件中替换它? 我尝试使用“a”而不是“w”,但它创建了一组不同的字典,我收到一条错误消息,说 Json 只允许一个顶级值

import json
    web=input('web:')
    username=input('us:')
    pw=input('pw')
    account_data= {web: {'Email': username,'Password': pw}}
    try:
        with open('trial.json', 'r') as file:
            # save the previous data in json
            data = json.load(file)
            # update the json by appending the newer data into old data
            data.update(account_data)
    
    except FileNotFoundError:
        with open('trial.json', 'w') as file:
            # create data.json if it doesnt exist
            json.dump(account_data, file, indent=4)
    else:
        with open('trial.json', 'w') as file:
            # replace old json file with new one
            json.dump(data, file, indent=4)

输出:

{
    "face": {
        "Email": "asdqweerqr",
        "Password": "dregtertsdf"
    },
    "fasd": {
        "Email": "wqe",
        "Password": "asdf"
    }
}

输出总是替换现有的键值对。 谢谢

【问题讨论】:

  • 还提供您期望的结果。

标签: json python-3.x dictionary


【解决方案1】:

基本上你不能修改 python 字典的键。然而,删除旧密钥很容易。由于json 模块代表一个带有字典的 json 对象,这基本上是唯一的选择。

查看讨论Change the name of a key in dictionary

在 python 中从旧字典创建一个全新的字典并不少见,但删除不需要的键更容易也更有效。

PS。有一些花哨的 python json 库可以让你更改 json 键。此外,在 pandas 和 JavaScript 中,您可以轻松修改 json 键。另一个简单的技巧是首先将字典序列化为字符串,替换键,然后将字符串保存到文件中,但这在极端情况下会变得很棘手。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2016-06-02
    • 2018-09-23
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多