Reputation: 21241
I have a strange requirement.
I have a method (posting only relevant code, not full code.)
def updateLevelFile(level, __data, mode='r+', encoding='utf-8'):
# I want this to be dynamic
__data[index]["tasks"][0]['choices'][0]["4"] = str(host['httporhttps'])
# I want this to be dynamic
Need # I want this to be dynamic
section to be dynamic.
means I will pass this method which keys to update and the values too ..
Keys can be different each time, for some instances we can have key ["tasks"][2]["task_default_text"]
How to do it?
Whole code in this method is being used so many times, I don't want to replicate it, I want to make it a method and call again and again.
WHAT I HAVE TRIED?
I have tried to pass
'"tasks": [{"choices": [{"4": "1"}]}]'
equivalent JSON of ["tasks"][0]['choices'][0]["4"]
and decoded into dictionary
and then do something like __data[index]to_update
but its obviously invalid syntax.
Upvotes: 0
Views: 81
Reputation: 56467
Try this (assuming I understand your question correctly):
def set_value_for_path(obj, path, value):
for key in path[:-1]:
obj = obj[key]
# Note: will raise an exception if path is an empty list
obj[path[-1]] = value
and in your function
set_value_for_path(
__data[index],
("tasks", 0, 'choices', 0, "4"),
str(host['httporhttps'])
)
Now you can turn second argument of set_value_for_path
function into updateLevelFile
function param, e.g.
def updateLevelFile(level, __data, mode='r+', encoding='utf-8', path):
# ...
set_value_for_path(__data[index], path, str(host['httporhttps']))
# ...
updateLevelFile(level, __data, 'r+', 'utf-8', ("tasks", 0, 'choices', 0, "4"))
Upvotes: 2
Reputation: 1011
You can use kwargs, a example below to give an idea.
def updateLevelFile(level, __data, mode='r+', encoding='utf-8', **kwargs):
task_index = kwargs.pop('task_index')
key = kwargs.pop('key')
key_index = kwargs.pop('key_index')
__data[index]["tasks"][task_index][key][key_index]["4"] = str(host['httporhttps'])
#Example function call
updateLevelFile(level, __data, task_index=2, key="task_default_text", key_index=2)
Upvotes: 2