0

How can I pass a dictionary path as an argument? I thought maybe it had something to do with *args or **kwargs but I didn't understand how to use them for this

dictionary = {
    'key1': {
        'attribute1': 'green',
    },
    'attribute2': 5
}
def SaveToFile(target, value):
    with open('savefile.json', 'r') as savefile:
        dictionary = json.load(savefile)

    dictionary[target] = value

    with open('savefile.json', 'w') as savefile:
        json.dump(dictionary, savefile)

SaveToFile('["key1"]["attribute1"]', 'blue')
SaveToFile('["attribute2"]', 10)
print(dictionary)

desired output:

{
    'key1': {
        'attribute1': 'blue'
    },
    'attribute2': 10
}


2
  • 1
    stackoverflow.com/questions/47969721/… though why not just do ChangeValue(dictionary["key1"]["attribute1"], 'blue') and set that target equal to value? Commented Oct 30, 2022 at 8:20
  • @AndrewRyan I edited the question to better illustrate my needs. I don't have dictionary until the file is read so it can't be passed in the arguments Commented Oct 30, 2022 at 8:51

1 Answer 1

1

use regex and recursion to solve this

dictionary = {
    'key1': {
        'attribute1': 'green',
    },
    'attribute2': 5
}
import re

def update_dict(d_, val, *keys):
    if not keys:
        return {}
    key = keys[0]
    
    if isinstance(d_[key], dict):
        d_[key].update(update_dict(d_[key], val, *keys[1:]))
    else:
        if key in d_:
            d_[key]= val
    return d_
    

def ChangeValue(target, value):
    keys = filter(lambda x: bool(x), re.split('\[\"(.*?)\"\]', target))
    update_dict(dictionary, value, *keys)


ChangeValue('["key1"]["attribute1"]', 'blue')
ChangeValue('["attribute2"]', 10)
dictionary
# output {'key1': {'attribute1': 'blue'}, 'attribute2': 10}
Sign up to request clarification or add additional context in comments.

3 Comments

I updated my question to better illustrate my needs. Will this still work?
yes this will work, you can check
@thelovedolphin i will update my answer to accommodate this. You need to add sample example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.