Jj's web stream

Concatenating dicts in #Python

Sometimes, I just want to inline everything or make all my #Python statements be as flat as possible and list and dict comprehensions are amazing for this. Making my code less readable and giving me a false impression of speed, coworkers may unprefer, but oh I love how it looks.

But dicts always bummed me, I wanted to "sum" them and I had no operation for such thing, rather than calling .update() on separate lines since it cannot be chained.

I always liked dict literals over the dict() function, and very rarely used it until I found that it can do exactly what I wanted. Turns out it has two behaviors.

Given dict a = {"a": 1} and I want to add a few keys to it. I could use the the following syntax:

joined = dict(a, b=2, c=3)

Which would return what I wanted without altering a and without having to do it the boring way:

joined = {}
joined.update({"b": 2, "c": 3})

Cool!

Ok, but what when I have my keys in many dicts?

Turns out that given b = {"b": 2} and c = {"c": 3} I can do the following:

joined = dict(a, **b)
joined = dict(joined, **c)

Or even better:

joined = reduce(lambda x, y: dict(x, **y), [a, b, c])

And there I got it! The inline adding of dicts. Ugly syntax, requires a lambda, little readability, not necessarily faster, but hey! It is in one line and will make all your code look nicely unindented ;)

Shared on:

Jj Avatar of Jj