Programming, Python

Keyword arguments and merging dictionaries

There are rules for where *args and **kwargs appear in function declarations.

Everything before *args is a non-keyword parameter. Everything after *args is a keyword parameter and cannot be passed by position.

You can have parameters with defaults anywhere in the declaration, but if **kwargs is present, it must be the last thing in the declaration.

There is one other thing to be aware of, and that’s Python’s copying mechanisms when it comes to dictionaries. Consider this code snippet:

a = {'one':1,
     'two':2}
b = a
a['three'] = 3

You would think this would yield a backup copy of a in dictionary b, and a would get a new key ‘three’ with value 3.

That’s not the case.

When you set b equal to a, because Python doesn’t copy dictionaries with an actual copy, you get two references to the same dictionary. If you modify a, you’ll see the changes in b, too. Modify b, and a is changed.

What you probably meant is:

a = {'one':1,
     'two':2}
b=a.copy()
a['three'] = 3

The copy method of a dictionary does the copy you’re looking for – sort of. It’s a shallow copy, meaning you get a new dictionary, but the elements are still references to the same objects in the first dictionary.

This might be a better method:

import copy
a = {'one':1,
     'two':2}
b=copy.deepcopy(a)
a['three'] = 3

But it also might not be a better method. If dictionary a has recursive references to itself, then you can hit recursion exceptions.

Also, you might want separate references to the same object.

I think this is an area where Python could improve, but answers to questions like this have side effects. Best to remain aware of how Python copies data and let the language evolve.

In the general case, this is not a problem, anyway.


Confusing? Nope, not at all. If we got together with the back of an envelope in your company break room, you’d have this down cold in ten minutes.

You would (cough) need to hire me, of course, so we could both be welcome in your break room, but that’s OK. As it just so happens, I’m looking for a job.

Questions about Python or where to set up payroll direct deposit can be resolved with the Get in Touch! link at the top of this page, the comments below, or by email to carl@carlhaddick.com.