Home > database >  How to check if key/value already exist in .json
How to check if key/value already exist in .json

Time:12-29

So this is my config.json

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

and this is my code

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)

I want to check if name = "A" already exist or not, if already exist it gonna cancel the input, if not exist write_json will run it func

CodePudding user response:

Given a list of dictionaries, you can check a condition on each one with 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() will return True at the first item that is True from the iterable, and False if none match (like F).

CodePudding user response:

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

i'd loop through each entry and compare each name

  • Related