I’m sorry for the crazy title. I’m new to programming and have no idea what I’m doing.
I’m making a weight tracker that saves data to a JSON.
The data is a nested dictionary that supposed to look like:
{
"Dates": {
"11/11/11": {
"Morning": 500,
"Night": 502
}
}
}
I’ve been trying to make the tracker ask for date input, and use that input as a new value for the "Dates" key aslong as the date doesnt already exist, and if it does exist to then append new values to the Morning or Night keys based on user input.
Here is my code:
weight_date_dict = open('main.json')
today = input("Enter the date(MM/DD/YY): ")
data = json.loads(weight_date_dict.read())
if today not in data:
data['Dates'] = today
answer = input("Morning or Night? (Case sensitive): ")
if answer == "Morning":
m_weight = input("Weight? ")
#ERROR: Cant index a string('Dates') with a string(today)
data['Dates'][today]['Morning'] = m_weight
elif answer == "Night":
n_weight = input("Weight? ")
data['Dates'][today]['Night'] = n_weight
else:
print("Please enter Morning or Night.")
After solving how to write to the json without overwriting the previous dictionary keys/values inside of it, I added:
if today not in data:
data['Dates'] = today
data['Dates'][today] = {'Morning': None, 'Night': None}
to add a new date, which came up with "TypeError: ‘str object does not support item assignment’"
The line data['Dates'][today]['Morning'] = m_weight
, which is supposed to append a new value to the Morning or Night keys, doesnt work because strings can’t be indexed by strings.
And I cant figure out how to append values to a date that already exists since its user-inputted. I feel like I’m completely off on how to do this.
2
Answers
You should check for the date in the subobject identified by the
"Dates"
key, and set it to an empty object if it doesn’t exist yet.In addition, you need to convert the user input from str to int.
Finally, use
json.dump
to write the updated version to the file at the end of the program.Your code has a few issues:
First,
doesn’t do what you think it does.
today not in data
checks iftoday
exists indata
, but all your actual data is indata['Dates']
. Also, by doingdata['Dates'] = today
, you overwrite all that data. What you really want to do is this:That’s why you get the error later on when you try to do
data['Dates'][today]
.data['Dates']
is no longer a dictionary of your data, its a string of today’s date.Your code also has a few other issues, such as not converting user input from a string to an integer. I also made some changes to reduce the code and make it a bit cleaner. Here’s the full code that I got working for you: