I have the following python dictionary:
box = {
'name': 'Test',
'length': 10,
'width': 20
}
I need to keep a reference to this object when passing it into a function that modifies it.
The function will provide missing default information (height in this example):
def update_box(params):
defaults = {
'name': 'Default',
'length': 5,
'width': 5,
'height': 5
}
defaults.update(params)
params = defaults
return params
Now I need to access properties of box from outside the function. For example:
box = {
'name': 'Test',
'length': 10,
'width': 20
}
update_box(box)
print box['name'] # should output 'Test'
print box['height'] # should output 5
Of course, this doesn't work because the params = default line in the update_box
function reassigns params to defaults, for which there is no reference outside of update_box.
If I remove that line, then box is not modified.
What I would like to do is have some sort of inverse of the dict update() method that will
allow me to "fill in the blanks" for the object with default values while still keeping a reference to the original object.
What is the best way to do this?
Also, This example is simplified, so I can't just use the return value from update_box. Thanks for your help!
1 Answer 1
You can just update in both directions:
defaults.update(params)
params.update(defaults)
The first update ensures that the values originally in params are preserved, while the second modifies params directly.
Or, just do the update manually:
for k in defaults:
params.setdefault(k, defaults[k])
However, a better option might be to simply return a new dict, rather than directly modifying the original one.
2 Comments
setdefault?setdefault is simpler.
params.update(defaults)?params. Printingbox['name']would result in "Default" instead of "Test"{name: 'Test'}will try to look up thenamevariable and use its value as a key.