Sounds like you want to load a dictionary from json, add new key values and write it back. If that's the case, you can do this:

with open('python_dictionary.json','r+') as f:
    dic = json.load(f)
    dic.update(new_dictionary)
    json.dump(dic, f)

(mode is 'r+' for reading and writing, not appending because you're re-writing the entire file)

If you want to do the append thing, along with json.dumps, I guess you'd have to remove the first { from the json.dumps string before appending. Something like:

with open('python_dictionary.json','a') as f:
    str = json.dumps(new_dictionary).replace('{', ',', 1)
    f.seek(-2,2)
    f.write(str)
Answer from Munick on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to append an dictionary into a json file?
r/learnpython on Reddit: How to append an dictionary into a json file?
September 2, 2023 -

Hello I currently learning json in python i want to append a dictionary in a json file ontop of existing ones but every time i do this i get this error in VS-Code:

End of file expected.

Can somebody help me?

Here is the Code:

dict = {
    "data1" : data3,
       
    "data2" : data4        
}
    
data = json.dumps(dict)
with open("index.json" , "a") as file:
    
    json.dump(data , file)

Discussions

python - How to add new dictionary into existed json file with dictionary? - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... It is not a valid json ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
August 6, 2018
json - Python: add to a dictionary in a list - Stack Overflow
I've tried using append/extend but that just adds a new dictionary to the list. ... I have tried looking on stack overflow already. please don't downvote my question. If you can find a question like this already asked, I'd really appreciate it. Asking a new question, means its my last resort. ... Can you share an example of the output you'd like to get? I fear I'm not following the question properly. ... I am trying to create a dict, for a future JSON... More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 27, 2020
Python, add dictionary to JSON file - Stack Overflow
60 dictionaries with 10-12 values. File is refreshing every second and after a few minutes file have ~15000 lines! ... You might be able to cache the contents of the JSON file so you don't have to load it every time...but you will need to write it out every time it's updated if it's important that the version on disk always contain all the latest additions... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 23, 2017
how to add a dicitionary to a json file. pls help coz im not able to find a good answers in stack overflow or gfg
Load the structure, append the dictionary to it, dump the structure back to the file. More on reddit.com
๐ŸŒ r/learnpython
8
1
September 27, 2022
Top answer
1 of 3
6

There are several questions here. The main points worth mentioning:

  • Use can use a list to hold your arguments and use *args to unpack when you supply them to add_entry.
  • To check / avoid duplicates, you can use set to track items already added.
  • For writing to JSON, now you have a list, you can simply iterate your list and write in one function at the end.

Putting these aspects together:

import json

res = []
seen = set()

def add_entry(res, name, element, type):

    # check if in seen set
    if (name, element, type) in seen:
        return res

    # add to seen set
    seen.add(tuple([name, element, type]))

    # append to results list
    res.append({'name': name, 'element': element, 'type': type})

    return res

args = ['xyz', '4444', 'test2']

res = add_entry(res, *args)  # add entry - SUCCESS
res = add_entry(res, *args)  # try to add again - FAIL

args2 = ['wxy', '3241', 'test3']

res = add_entry(res, *args2)  # add another - SUCCESS

Result:

print(res)

[{'name': 'xyz', 'element': '4444', 'type': 'test2'},
 {'name': 'wxy', 'element': '3241', 'type': 'test3'}]

Writing to JSON via a function:

def write_to_json(lst, fn):
    with open(fn, 'a', encoding='utf-8') as file:
        for item in lst:
            x = json.dumps(item, indent=4)
            file.write(x + '\n')

#export to JSON
write_to_json(res, 'elements.json')
2 of 3
1

you can try this way

import json
import hashlib


def add_entry(name, element, type):
        return {hashlib.md5(name+element+type).hexdigest(): {"name": name, "element": element, "type": type}}


#add entry
entry = add_entry('xyz', '4444', 'test2')


#Update to JSON
with open('my_file.json', 'r') as f:
    json_data = json.load(f)
    print json_data.values() # View Previous entries
    json_data.update(entry)

with open('elements.json', 'w') as f:
    f.write(json.dumps(json_data))
๐ŸŒ
Quora
quora.com โ€บ How-do-you-append-a-dictionary-to-a-JSON-file-Python
How to append a dictionary to a JSON file (Python) - Quora
Use json. load() , dict. update() , and json. dump() append to a JSON file ... There is no append function for dictionaries in python while list have. ... There is no append function for dictionaries in python while list have.
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ how to append data to a json file in python? [+video]
How to Append Data to a JSON File in Python? [+Video] - Be on the Right Side of Change
March 16, 2023 - To update a JSON object in a file, import the json library, read the file with json.load(file), add the new entry to the list or dictionary data structure data, and write the updated JSON object with json.dump(data, file). In particular, here are the four specific steps to update an existing ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ append-to-json-file-using-python
Append to JSON file using Python - GeeksforGeeks
March 26, 2024 - Syntax: json.dumps(object) Parameter: It takes Python Object as the parameter. Return type: It returns the JSON string. update(): This method updates the dictionary with elements from another dictionary object or from an iterable key/value pair.
Find elsewhere
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-json-to-dict
Python JSON to Dictionary
To convert Python JSON string to Dictionary, use json.loads() function.
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ convert json to dictionary in python
Convert JSON to Dictionary in Python - Spark By {Examples}
May 31, 2024 - You can convert a JSON string to a Python dictionary in Python using the json module. The json.loads() function is specifically designed for this purpose. For example, json_string is the JSON data in string format.
๐ŸŒ
Codesolid
codesolid.com โ€บ python-json-easily-work-with-dictionaries-files-and-custom-objects
Python JSON: Easily Work With Dictionaries, Files, and Custom Objects โ€” CodeSolid.com 0.1 documentation
This tutorial will show you how to work with Python JSON and dictionaries to encode and decode JSON. In addition to serializing dictionaries to and from JSON strings, the Python json module also includes methods to write and read Python dictionaries as Python files easily.
๐ŸŒ
HowToDoInJava
howtodoinjava.com โ€บ home โ€บ python json โ€บ python โ€“ append to json file
Python - Append to JSON File
December 9, 2022 - Learn to append JSON data into file in Python. To append, read the file to dict object, update the dict object and finally write the dict to the file.
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ how to convert json to a dictionary in python?
How to convert JSON to a dictionary in Python? - AskPython
February 16, 2023 - In this tutorial, we have learned how to read a JSON file and then convert it into a Python dictionary using json.load() function. Hope this topic is clear to you and you are ready to perform these operations on your own.
๐ŸŒ
Medium
medium.com โ€บ analytics-vidhya โ€บ python-dictionary-and-json-a-comprehensive-guide-ceed58a3e2ed
Python Dictionary and JSON โ€” A Comprehensive Guide | by Kiprono Elijah | Analytics Vidhya | Medium
January 11, 2024 - Python dictionary is a a collection of key-value pairs. Dictionary is mutable(can be changed), unordered and can be indexed. JSON is a data format...
๐ŸŒ
Index.dev
index.dev โ€บ blog โ€บ convert-json-to-dictionary-python
How to Convert JSON to a Python Dictionary: Step-by-Step Guide
This module lets you translate JSON texts and files into Python objects including dictionaries by parsing them. The simplest approach to translate a JSON-formatted text into a Python dictionary is with json.loads().
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ convert-json-to-dictionary-in-python
Convert JSON to dictionary in Python - GeeksforGeeks
July 12, 2025 - In the below code, firstly we open the "data.json" file using file handling in Python and then convert the file to Python object using the json.load() method we have also print the type of data after conversion and print the dictionary.
๐ŸŒ
SitePoint
sitepoint.com โ€บ python, perl and golang โ€บ python
Adding a new key to a nested dictionary in python - Python - SitePoint Forums | Web Development & Design Community
December 21, 2016 - JSON: {'result':[{'key1':'valu... list, like this: dict = {'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]} length = len(dict['result']) print(length) data_dict[......
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_json.asp
Python JSON
Python has a built-in package called json, which can be used to work with JSON data. ... If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.