Answer the question
In order to leave comments, you need to log in
How to write data to JSON along the way?
I have a json representing a dictionary filled with nested dictionaries. I want to write a function to which I could somehow pass the entire path so that it writes certain data along this path.
def user_write (chat, par,val):
users = {}
with open('data.json', 'r', encoding='utf-8') as file:
users = json.load(file)
with open('data.json', 'w', encoding='utf-8') as file:
users[chat][par] = val
json.dump(users, file, indent=4,ensure_ascii=False)
Answer the question
In order to leave comments, you need to log in
List elements can be accessed by index: user_list[3][0][2]
What exactly is the problem? What is the error text and sample data?
def set_value(data, index, value):
key = index.pop(0)
if len(index):
if key in data:
data_key = data[key]
else:
data_key = {}
data[key] = set_value(data_key, index, value)
else:
data[key] = value
return data
users_list = {0: {'name': 'vasya'}}
set_value(users_list, [0, 'age'], 16)
# {0: {'name': 'vasya', 'age': 16}}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question