return {**old, 'foo': 'bar'}
# Old way
return dict(old, foo='bar')
Not much difference if you ask me. return {**old, 'foo': 'bar'}
# Old way
return dict(old, foo='bar')
Not much difference if you ask me. {**x, 'fo'+'o': 'bar', **y}Personally I hate the new {} for set syntax.
Is {} an empty set, or an empty dict?
return dict(x, **{'fo'+'o': 'bar'}, **y)
The new syntax is some mild syntactic sugar. (Which isn't a bad thing IMO) Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = {'foo': 5, 'bar': 6}
>>> y = {'foo': 7, 'baz': 9}
>>> dict(x, **{'fo'+'o': 'bar'}, **y)
File "<stdin>", line 1
dict(x, **{'fo'+'o': 'bar'}, **y)
^
SyntaxError: invalid syntax
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = {'foo': 5, 'bar': 6}
>>> y = {'foo': 7, 'baz': 9}
>>> dict(x, **{'fo'+'o': 'bar'}, **y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type object got multiple values for keyword argument 'foo'
>>> {**x, 'fo'+'o': 'bar', **y}
{'foo': 7, 'baz': 9, 'bar': 6}Just skip all this and use Perl instead. You can write far more idiomatic, succinct readable code in Perl than you can in Python.
The whole point of Python is to not write code this way.
The expanded unpacking works in all cases.
X ++ {'fo'+'o': 'bar'} ++ y
Where '++' here means dictionary union, the choice of symbol is not relevant.
dict(a, ... ,b) feels cleaner.