【问题标题】:How to check if key/value already exist in .json如何检查.json中是否已经存在键/值
【发布时间】:2021-12-29 02:55:51
【问题描述】:

这是我的 config.json

{
"dictionary": [
    {
        "name": "A",
        "rollno": "B",
        "cgpa": "C",
        "phonenumber": "D"
    },
    {
        "name": "E",
        "rollno": "F",
        "cgpa": "G",
        "phonenumber": "H"
    }
]}

这是我的代码

import os
import json

name = input("Name : ")
rollno = input("No : ")
cgpa = input("cgpa : ")
phonenumber = input("Phone No. : ")
dictionary ={
            "name" : f"{name}",
            "rollno" : f"{rollno}",
            "cgpa" : f"{cgpa}",
            "phonenumber" : f"{phonenumber}"
    }

def write_json(data, filename="Discord\Test Field\config.json"):
    with open(filename,'r+') as file:
        file_data = json.load(file)
        file_data["dictionary"].append(data)
        file.seek(0)
        json.dump(file_data, file, indent = 4)

with open("Discord\Test Field\config.json", 'r') as f:
    json_load = json.load(f)
    name_in_dict = name in json_load
    if name_in_dict == True:
        print("Key already exist")
    else:
        write_json(dictionary)

我想检查 name = "A" 是否已经存在,如果已经存在则取消输入,如果不存在 write_json 将运行它 func

【问题讨论】:

    标签: python json


    【解决方案1】:

    给定一个字典列表,您可以使用any()检查每个字典的条件:

    config = {
        "dictionary": [
            {
                "name": "A",
                "rollno": "B",
                "cgpa": "C",
                "phonenumber": "D"
            },
            {
                "name": "E",
                "rollno": "F",
                "cgpa": "G",
                "phonenumber": "H"
            }
        ]
    }
    
    any(d['name'] == 'A' for d in config['dictionary'] )
    # True
    
    any(d['name'] == 'F' for d in config['dictionary'] )
    # False
    

    any() 将在可迭代的第一项 True 处返回 True,如果不匹配则返回 False(如 F)。

    【讨论】:

    • 所以我把它放在 config.json 中制作“config = ...”?并在 py 文件中添加最后 2 个命令行?
    • 我只是在这个例子中使用了config,因为你的外部字典没有命名——我需要给它命名。这可能与您调用的 json_load 相同。
    • 但是如果我想使用 if 语句呢?我的意思是我想检查“名称”输入是否已经存在
    • @MorpKnight 注意这两个表达式返回布尔值:True 或 False。这意味着您可以将if 放在他们前面。或者将它们保存到一个变量中并将if 放在它前面。这意味着你可以做name_in_dict = any(d['name'] == 'A' for d in config['dictionary'] )...
    • aaa 谢谢@Mark 我明白了
    【解决方案2】:
    json = {
    "dictionary": [
        {
            "name": "A",
            "rollno": "B",
            "cgpa": "C",
            "phonenumber": "D"
        },
        {
            "name": "E",
            "rollno": "F",
            "cgpa": "G",
            "phonenumber": "H"
        }
    ]}
    
    newPerson = {
            "name": "E",
            "rollno": "F",
            "cgpa": "G",
            "phonenumber": "H"
        }
    
    def checkIfNameExists(fileData, newEntry):
        for entry in fileData:
            if entry["name"] == newEntry["name"]:
                return False
        return True
    
    print(checkIfNameExists(json["dictionary"], newPerson))
    

    我会遍历每个条目并比较每个名称

    【讨论】:

    • 看着这个我可以说我很匆忙,@mark 的答案可能更适合你
    • 好的,但是感谢您的帮助
    • np,如果标记答案有效,请务必将答案标记为解决方案,(左侧的勾号,在投票箭头下方)
    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2016-03-29
    相关资源
    最近更新 更多