What is the method for including an item in a Dictionary?

I encountered an issue with a nested dictionary in a Json file. Here is the current content of the file (highscore_history.txt):

{
    "Highscores": {
        "0highscore": 2
    }
}

My goal is to add a new entry into the nested dictionary...

with open("highscore_history.txt", "w") as Highscore_history_txt:
    highscore_history["Highscores"].update({f"{last_element_of_the_history}highscore": main_game.current_highscore[-1]})
    json.dump(highscore_history["Highscores"], Highscore_history_txt, indent =4)
    saved_highscores = {f"{last_element_of_the_history} highscore": main_game.current_highscore[-1]}

However, when I implement this code snippet, the new key-value pair appears outside the second dictionary:

{
    "Highscores": {
        "0highscore": 2
    },
    "1highscore": 0,
}

I am seeking guidance on how to ensure that the new entry is properly added inside the nested dictionary.

Answer №1

Update

Here is a quick example demonstrating how to add new data to a JSON file while maintaining the same structure.

Original JSON:

{
  "Highscores": {
    "0highscore": 2
  }
}

Code snippet:

import json

def write_json(data):
    with open("data.json", "w") as f:
        json.dump(data, f, indent=2)


with open('data.json') as json_file:
    data = json.load(json_file)
        
data['Highscores']['1highscore'] = 0
write_json(data)

Updated JSON:

{
  "Highscores": {
    "0highscore": 2,
    "1highscore": 0
  }
}

​​​

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

transform a JSON file containing multiple keys into a single pandas DataFrame

I am trying to convert a JSON file into a DataFrame using json_normalize("key_name"). I have successfully converted one key into a DataFrame, but now I need to convert all keys into one single DataFrame. { "dlg-00a7a82b": [ { "ut ...

Progress Bar in wxPython is an essential tool for tracking

Instead of using the wx.ProgressDialog, I am looking for a control that only includes the progress bar so I can add extra features like a pause button and processing information to my own dialog box. I could design something myself, but in order for the p ...

Generate a dynamic JSON object based on grouped data from a DataFrame by a specified column name

I am currently working on a project that involves creating datasets using the columns of a dataframe. The columns I have to work with are ['NAME1', 'EMAIL1', 'NAME2', 'EMAIL2', NAME3', 'EMAIL3', etc]. ...

Using jQuery's .getJSON method will allow you to retrieve JSON data, however, you may encounter difficulty accessing

When making a call to the REST server using $.getJSON(url).done(function(data) {});, I encountered the following response: [ "{" id":1, "medname":"Medication No. 1", "qty":"2", "pDay":"3", "beforeAfterMeal":null }", "{ "id":3, "medn ...

Guide to retrieving a JSONArray using JavascriptInterface

I attempted to collect form data from an HTML using Javascript and send it back to Java as a JSONArray. However, I am encountering issues with the correct return of the JSONArray in the JavaScriptInterface. The JavaScript functions flawlessly in Chrome, i ...

View a specific selected newsAPI article on its own dedicated page

I have been working on a news website and successfully displayed all the articles on a single page using the news API in nodeJs. Everything is functioning well, but now I want to show the clicked article on a separate page. Although I managed to route it t ...

The information stored in Flask sessions is not retained across different sessions

Currently, I am constructing a website using React alongside Python with Flask. An issue has arisen where the session data is being lost between sessions and the cause remains unknown. Within the app.py file in Python, you can find the following app confi ...

Does the JSON property that exists escape NodeJS's watchful eye?

I recently encountered an unexpected issue with a piece of code that had been functioning flawlessly for weeks. In the request below and snippet of the response: //request let campaignRes = request('POST', reqUrl, campaignOptions); //response ...

Change the input field to uppercase using JavaScript but do not use inline JavaScript

Hey there! I have a basic script set up (see below) with an input field allowing users to enter a query. This query is then sent to a socrata webservice to request specific data, which is displayed in an alert box. So far, everything works smoothly. var l ...

Is there a way in MySQL to compare JSON data from one table with a set of ID values from another table using JSON_OVERLAPS function?

I'm dealing with two MySQL tables structured like this: first_table: the "json_field" column contains lists of integers, but is defined as type "json": id json_field 1 [1,2,3] 2 [2,3] 3 [1,3] second_table: a straightforward table with 2 c ...

Looking for a Python library that supports proxy for Twitter Streaming API?

Anyone know of a Python library for the Twitter Streaming API that supports proxies? I like tweepy, but haven't found a way to use an HTTP proxy. Any suggestions? ...

Utilize df columns for interactive interaction and apply a filtering operation using a string matching statement

Picture a dataset with several columns, all beginning with carr carr carrer banana One Two Three Is there a way to filter out only the column names that start with "carr"? Desired outcome carr carrer One Two Example dataframe: import pan ...

Linking a function to multiple labels with the same name - tkinter

I need to create a feature that allows users to generate multiple labels by pressing the "Enter" key: def new_line(event): global Row_n Row_n = Row_n + 1 Choose= tk.Label(frame, text="Choose option", background = "white",fo ...

What is the process for implementing a filter to retrieve specific information from the data.gov.in API?

I am currently working on accessing air traffic data for my region using the data.gov.in API. Here is the link to the API I am utilizing. I am interested in learning how to implement a filter to acquire specific city data, such as Noida. ...

Creating a visual grid using a combination of x's and blank spaces arranged in rows according to user input

As part of my computer programming homework (for Year 8 in the UK), I need to create a program based on the following criteria: Develop a function that takes two numbers as parameters. The first number determines the amount of spaces to be displayed, while ...

How can I exit a terminal window with the help of Python?

After extensive research on the web, I was unable to find any information on how to properly close a terminal using Python code. The code snippet I tried using is as follows: if optionInput == "6": exit() This code successfully exits the script ...

Combining a web-based login system with a duo device management client library

Seeking advice on integrating Duo device management portal (DMP) libraries into a website for baking. Currently, we have a functioning web page with ldap authentication served through Apache on a Linux server. Users must input their ldap credentials to ac ...

Changing Serializer Fields on the Fly in Django Rest Framework

I am attempting to utilize the Advanced serializer method outlined in the Django Rest Framework documentation. in order to dynamically modify a serializer field. Below is my customized serializer class: class FilmSerializer(serializers.ModelSerializer): ...

Django Dropdown Checkbox

I implemented a form in my Django application that includes a dropdown menu. Models.py class Quiz(models.Model): mtypes = (('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D') ...

Generating a numpy data type using a Cython structure

Displayed here is a segment of Cython code that is currently utilized in scikit-learn binary trees: # Some compound datatypes used below: cdef struct NodeHeapData_t: DTYPE_t val ITYPE_t i1 ITYPE_t i2 # build the corresponding nump ...