This is the 3rd in a series covering Pythonic code written by Michael Kennedy of Talk Python To Me. Be sure to catch the whole series with 5 powerful Pythonic recommendations and over 45 minutes of video examples.
DICTIONARIES ARE IMPORTANT
Dictionaries play an absolutely central role in Python. In fact, the previous two tips both touched on dictionaries in one way or another.
This tip is about merging dictionaries.
Let’s imagine we are writing a web application in Python. You’ll see that your action methods will receive data from several locations. Consider a web form at the URL server.com/customer/edit/271/Fast&20apps?id=1&render_fast=True.
On that page, there is a form with the data email = [email protected] and name = Jeff.
This data may appear in three dictionaries. One for the route, one for the query string and one for the form data. Now try to put yourself in the shoes of the web developer and answer the question ‘where do I get the ID from (which dictionary)?’ What if it’s missing from one, where do I fall back to?.. It’s not obvious is it? This is not clean code.
THE SOLUTION: MERGING DICTIONARIES
We can fix it by merging the dictionaries into a master “submitted data” dictionary with the right priorities.
But how do we do this merge? There is the super non-Pythonic version written procedurally as:
merged = {} for k in query: merged = query[k] for k in post: merged = post[k] for k in route: merged = route[k]
Yuck.
There are three additional ways to accomplish this merge that are more Pythonic. In Python 3.5, a new syntax was added to accomplish the code written above (including the prioritizing of route > post > query).
merged = {**query, **post, **route}
Nice, right? Check out the video demonstrating this to see all four ways in action.
VIDEO: MERGING DICTIONARIES CLEANLY IN PYTHON
You can find the code from this video on GitHub.
Michael Kennedy
@mkennedy
‘Ello, I’m Jamal – a Tokyo-based, indie-hacking, FinTech software developer with a dependence on data.
I write Shakespeare-grade code, nowadays mostly in Python and JavaScript and productivity runs in my veins.
I’m friendly, so feel free to say hello!