editing a dictionary in a json file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

editing a dictionary in a json file

When using the json library in Python, is it possible to add a new key:value pair to an already existing dictionary in a json file? I'm asking because any dictionary stored in a json file doesn't have a variable name, so it seems impossible to edit a particular one, I've only been able to add a new dictionary after the one I want to edit.

14th Nov 2017, 12:06 PM
Owolawi Kehinde
Owolawi Kehinde - avatar
7 Answers
+ 3
import json with open('data.json', 'w') as fp: json.dump(data, fp) Supply extra arguments like `sort_keys` or `indent` to get a pretty result. The argument *sort_keys* will sort the keys alphabetically and *indent* will indent your data structure with `indent=N` spaces.
14th Nov 2017, 12:11 PM
MsJ
MsJ - avatar
0
I don't see how this allows me to add a new 'key:value' pair to an already existing dictionary in a json file
14th Nov 2017, 12:57 PM
Owolawi Kehinde
Owolawi Kehinde - avatar
14th Nov 2017, 3:01 PM
yuri
0
as I see it, you just open the json file in a simple text editor, like Notepad and add a pair "new_key": value
14th Nov 2017, 3:03 PM
yuri
0
I can't do it manually through a text editor cause I'm trying to compile a code that automatically puts a user input into an already existing dictionary in a json file, so that the dictionary can be worked on as a whole unit.
14th Nov 2017, 3:19 PM
Owolawi Kehinde
Owolawi Kehinde - avatar
0
OK. in that case there are two ways: 1)load json file, amend the dictionary, and dump back (as new json foile); 2)read a few lines of json file, add new pair, write new file pretending it is json (without actually using json module). that can be done by any other code, not necessary Python or JS
14th Nov 2017, 5:11 PM
yuri
0
Yh thanks a lot. I just realized I can write a code to store the inputs in a txt file and write a code to store the contents of txt file in a json file
14th Nov 2017, 5:38 PM
Owolawi Kehinde
Owolawi Kehinde - avatar