0

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!

asked Jul 23, 2013 at 16:38
4
  • Why not use params.update(defaults)? Commented Jul 23, 2013 at 16:41
  • Because that will overwrite values in params. Printing box['name'] would result in "Default" instead of "Test" Commented Jul 23, 2013 at 16:45
  • Note: In Python, unquoted keys in dict literals are variables, not strings. {name: 'Test'} will try to look up the name variable and use its value as a key. Commented Jul 23, 2013 at 16:47
  • Thanks @user2357112. I updated my question accordingly to avoid confusion. Commented Jul 23, 2013 at 16:51

1 Answer 1

2

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.

answered Jul 23, 2013 at 16:45
Sign up to request clarification or add additional context in comments.

2 Comments

Why not setdefault?
Sure, setdefault is simpler.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.