def set(myDict, newValue, *keys): temp = myDict for key in keys[:-1]: temp = temp[key] temp[keys[-1]] = newValue myDict = { "credentials": { "private_key": "private/client-node.key", "root_ca": "ca.crt", "certificate": "client-node.crt" }, "connection": { "retry_timeout": 3, "disconnect_timeout": 50, "operation_timeout": 10, "host": "amya-iot-server.local", "retry": -1, "port": 8883, "keepalive": 600 }, "client": { "client_id": "" }, "topics": { "data": "data", "error": "data/error" }, "publish": { "retry_timeout": 3, "qos": 1, "retry": -1 }, "super" : { "deep": {"nested":{"thing":"yay!"}} } } #print original dictionary print(myDict) #update the dictionairy keys = ["connection", "port"] newValue = 1883 set(myDict, newValue, *keys) #print the dictionairy again (you should see the updated value) print(myDict) keys = ["topics"] newValue = {"somenewkey":"somenewvalue"} set(myDict, newValue, *keys) print(myDict) keys = ["super", "deep", "nested", "thing"] newValue = "booyeah!" set(myDict, newValue, *keys) print(myDict)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question