DEV Community

Maria Boldyreva
Maria Boldyreva

Posted on

Updating a dict in python

I've been a python dev for more than two years and somehow I didn't know that dicts can be updated by kwargs. Like this:

>>> a = {'a': 1}
>>> a.update(b=5)
>>> a
{'a': 1, 'b': 5}

So obvious, yet.

Top comments (3)

Collapse
 
rhymes profile image
rhymes • Edited

The only drawback of this is that update does not return anything so you can't use it in an expression.

There's an alternative in Python 3.5+:

c = {**a, **b}

this way you can merge dictionary a with b (or an in-line dict). c is the result, a and b remain unchanged.

Collapse
 
mxl profile image
Maria Boldyreva

Thanks Rhymes!

Collapse
 
davcastroruiz profile image
David Castro

I learned it thanks to Django and csrf token :)

dictionary = dict(request=request, message=message)
dictionary.update(csrf(request))

regards :)