Member-only story
3 More Tricks To Shorten Your Python Code by a Couple of Lines
Figuring out how to write the same program with less code has always been one oddly satisfying task for me. Sure, I reduce my code by a couple of lines here and there — how transformative! Regardless, here are 3 Python tricks that we can use to shorten our code by a couple of lines!
Dictionary Get Method
Let’s say we have a dictionary:
fruits = {
"apple": 4,
"orange": 5,
"pear": 6
}
And we want to pass in a key to the dictionary, return the value if the key exists, and return a default value if the key does not exist. Here’s how we might do this:
key = "apple"if key in fruits:
value = fruits[key]
else:
value = "default value"
With the dictionary get function, we can shorten this to one line.
value = fruits.get(key, "default value")
The .get function essentially does the same thing as the if-else block above — if the key exists in the dictionary, return the value. Else, set value as whichever default value.
Dictionary Items Method
As newer Python coders, this is how we might iterate through a dictionary: