How to make a copy of chained dicts effectively and nicely?

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Tue Sep 27 09:27:24 EDT 2016


Lawrence D’Oliveiro writes:

> On Tuesday, September 27, 2016 at 8:08:46 PM UTC+13, Nagy László Zsolt wrote:
>> d1 = {'a':1, 'b':2}
>> d2 = {'c':3, 'd':4}
>> d3 = {'e':5, 'f':6}
>> 
>> Is there a version that is as effective as #3, but as clean and nice as #4?
>
> dict(dict(d1, **d2), **d3)

Nice expression. But that's not available if the keys are not strings:

dict({}, **{ 1:3 })
==>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings

On the other hand, '1' seemed to work (in Python 3.4.3) as key, though 1
cannot possibly be a keyword parameter in a function definition :)

Also related to the use of **, are there any practical limitations to
how many parameters a Python function may have? Or is it guaranteed safe
to spread, say, hundreds of thousands of dictionary keys this way? Just
wondering.



More information about the Python-list mailing list