The original code looks up the value in the dictionary just once, storing the result in a variable. Your alternative looks up the value twice, via get() and via [].

This is a possible source of bugs. For example if the element name was changed to ‘heading’ it is possible that the developer might only change the first occurrence and not realise it needed changing somewhere else. So you would be testing for the existence of one element, then retrieving a different element to print.

It is also usually going to be less efficient, although of course that isn’t always going to be a significant consideration.

With := you get the best of both world, fewer lines of code without repeating potentially expensive operations.

Written by

I am a software developer with over 30 years experience in Java, Python and C++. I write for pythoninformer.com.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store