简体   繁体   中英

def python function would not return

So I want to make inventory from the JSON file and Why this code won't return anything?

import os
import json

def get_data():
    with open(os.path.dirname(os.path.realpath(__file__))+"/items.json") as f:
        data = json.load(f)
    return data

def save_data(data):
    with open(os.path.dirname(os.path.realpath(__file__))+"/items.json", "w") as f:
        json.dump(data, f, indent=4)

def modify_item(name,category,mode):
    data = get_data()
    temp = data[str(category)]
    y = {str(name): 1}
    if mode == "+":
        for index in range(len(temp)):
            if data[str(category)][int(index)][str(name)] == str(name):
                data[str(category)][int(index)][str(name)] += 1
        return data
    elif mode == "-":
        data[str(category)][int(index)][str(name)] -= 1
        return data
    elif mode == "a":
        temp.append(y)
        return data

save_data(modify_item(name="Potato fries", category="Foods", mode="+"))

The json file

{
    "Foods": [
        {
            "Potato fries": 1
        }
    ],
    "Misc": [
        {
            "Disc": 1
        }
    ]
}

It won't change the "Potato fries" key. The console just did not show the errors, Someone explain why?

In the "+" mode, your condition is never fulfilled, because you are comparing the name (string) to the value of the field name in your dictionary (in this case an int).

Surely not the best/cleanest way to do it but it works if you just replace your if with a try and except statement:

try:
    data[str(category)][int(index)][str(name)] += 1
except:
   print("Name given is not in the available categories.")
   break

https://www.w3schools.com/python/python_try_except.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM