🐍 Python tricks I did not know about ✨

Rishav Nath Pati
9 min readApr 15, 2023

--

👋 Hey there, Pythonistas! Are you ready to level up your Python game? 💪🐍

Whether you’re a seasoned software developer or a 🆕 Python learner, there’s always room for some cool tricks and tips to enhance your Pythonic skills.

That’s why we’ve gathered a bunch of 🤓 clever Python snippets and tricks that you may not have known about. From 🚀 speedy shortcuts to 🔮 magical hacks, we’ve got some surprising ways to work with Python that’ll blow your mind.

So, get ready to 🤯 be impressed and amazed as we unveil some of the most useful Python tricks out there. Let’s dive in! 🌊

1. Merging two dictionaries in Python 3.5+

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}

z = {**x, **y}
print(z) # {'c': 4, 'a': 1, 'b': 3}

🤝📚 Merge two dictionaries like a pro with Python 3.5+! No need to write long loops or confusing code — just use the unpacking operator (**).

👉 Check out this simple example: we have two dictionaries x and y, and we want to combine them into one dictionary z. Just use {**x, **y} and voilà!

🔍 Note that in the resulting dictionary, keys from the second dictionary (y) overwrite keys from the first dictionary (x) if they have the same name. It’s like a royal rumble of keys, where the winner takes all!

Merging dictionaries in Python 2.x

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}

z = dict(x, **y)
print(z) # {'a': 1, 'c': 4, 'b': 3}

🎓 If you’re still stuck on Python 2.x, don’t worry, we’ve got you covered too. Just use dict(x, **y) and you'll get the same result. It's like a dictionary union, where everyone gets along and shares their keys.

2. 🔍🚦 Testing multiple flags in Python

No problem! Here are four clever ways to check for multiple conditions at once:

x, y, z = 0, 1, 0

# Check each flag separately
if x == 1 or y == 1 or z == 1:
print('passed')

# Use the "in" keyword
if 1 in (x, y, z):
print('passed')

# Test for truthiness (can be risky!)
if x or y or z:
print('passed')

# Use the "any" built-in function
if any((x, y, z)):
print('passed')

👀 Keep your code concise and clean by testing multiple flags at once. You can use the or keyword, but it can get a bit lengthy.

💡 Instead, you can use the in keyword to check if a value is present in a sequence of values (such as a tuple).

👉 Or, if you want to test for truthiness, you can use the logical or operator to check if at least one flag is "true".

🤖 For a more flexible and efficient solution, you can use the any() built-in function with a tuple of flags as its argument. It checks if at least one value in the sequence is "truthy".

3. 🔍🔤 Sorting a dictionary by value in Python

Look no further! Here are two ways to sort a dictionary by value and get a new dictionary with the keys sorted in descending order:

xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

# Using lambda function
sorted_dict = sorted(xs.items(), key=lambda x: x[1])
print(sorted_dict) # [('d', 1), ('c', 2), ('b', 3), ('a', 4)]

# Using operator module
import operator
sorted_dict = sorted(xs.items(), key=operator.itemgetter(1))
print(sorted_dict) # [('d', 1), ('c', 2), ('b', 3), ('a', 4)]

🤔 Confused about how to sort a dictionary by its values instead of its keys? No problem! Just use the sorted() function with the key argument, and pass a lambda function or operator.itemgetter() to specify the value to sort by.

💡 The lambda function takes an item (a key-value pair) and returns the value. This is used to sort the dictionary by value.

🤖 Alternatively, you can use the operator.itemgetter() function to specify the index to sort by. In this case, we use 1 to sort by the value (since the items are (key, value) tuples).

👉 Both methods return a sorted list of key-value pairs, which you can convert back to a dictionary using the dict() constructor.

4. The get() method on Python dicts and its “default” arg

👋🏼🐍 Say goodbye to KeyError when looking up values in a dictionary with the get() method in Python! Here's an example:

name_for_userid = {
382: "Alice",
590: "Bob",
951: "Dilbert",
}

def greeting(userid):
return "Hi %s!" % name_for_userid.get(userid, "there")

print(greeting(382)) # "Hi Alice!"
print(greeting(333333)) # "Hi there!"

🤖 The get() method retrieves the value for a given key in the dictionary. If the key is not found, it returns the default value (which is "there" in this example).

💡 This is useful when you want to handle missing keys gracefully, without raising a KeyError. In this case, we use get() to look up a user's name by their ID number, and if the ID is not found, we return a generic greeting instead of raising an error.

👍🏼 The get() method can also be used to provide a default value of None if no default argument is provided. This is equivalent to using the in operator to test for key existence, but without the need for an additional if statement.

5. 👨‍💻🐍 Want to define a class quickly and easily in Python? Try using namedtuples!

🚗💥 Namedtuples are a great alternative to defining a class manually. They’re shorter, simpler, and just as powerful. Here’s an example:

from collections import namedtuple

# Define a Car class using a namedtuple
Car = namedtuple('Car', 'color mileage')

# Create an instance of the Car class
my_car = Car('red', 3812.4)

# Access attributes of the Car class
print(my_car.color) # 'red'
print(my_car.mileage) # 3812.4

# Get a nice string representation for free
print(my_car) # Car(color='red', mileage=3812.4)

# Namedtuples are immutable, like tuples
my_car.color = 'blue' # Raises an AttributeError

📜💡 Namedtuples work just like regular tuples, but with named fields. You can access the fields by name, or use the index like a regular tuple.

👍🏼 Namedtuples are a great way to define simple classes quickly and easily, without all the overhead of defining a full class manually. Plus, they’re lightweight and efficient, so you can use them wherever you need a simple data structure.

6. import this

I must say, import this is one of my favorite Easter eggs in Python. It prints out "The Zen of Python," which is a collection of guiding principles for writing computer programs in the Python language. It is a short and sweet set of aphorisms that serve as a reminder of what makes Python such a beautiful language to work with. If you haven't seen it before, give it a try by typing import this in your Python REPL!

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

7. Using “json.dumps()” to pretty-print Python dicts 📄

… (as an alternative to the “pprint” module)

The standard string repr for dicts is hard to read 😞:

>>> my_mapping = {'a': 23, 'b': 42, 'c': 0xc0ffee}
>>> my_mapping
{'b': 42, 'c': 12648430, 'a': 23}

The “json” module can do a much better job 👍:

>>> import json
>>> print(json.dumps(my_mapping, indent=4, sort_keys=True))
{
"a": 23,
"b": 42,
"c": 12648430
}

Note this only works with dicts containing primitive types (check out the “pprint” module) 😇:

>>> json.dumps({all: 'yup'})
TypeError: keys must be a string

In most cases, I’d stick to the built-in “pprint” module though 😉.

8. Function argument unpacking

Have you ever found yourself with a tuple or a dictionary, and needed to pass its values as arguments to a function? You could access each value one by one and pass them individually, but that can get tedious and error-prone.

Luckily, Python has a neat feature called argument unpacking that can help with that. With argument unpacking, you can pass the elements of a tuple as separate arguments or the key-value pairs of a dictionary as keyword arguments to a function.

Let’s see how it works with a simple example. Imagine you have a function myfunc() that takes three arguments: x, y, and z.

def myfunc(x, y, z):
print(x, y, z)

Now, suppose you have a tuple tuple_vec with three values that you want to pass as arguments to myfunc(). Instead of passing the tuple itself and letting the function deal with it, you can use the * operator to unpack the tuple into its three values and pass them as separate arguments to myfunc():

tuple_vec = (1, 0, 1)
myfunc(*tuple_vec)
# Output: 1 0 1

Similarly, you can unpack a dictionary dict_vec into its key-value pairs and pass them as keyword arguments to myfunc() using the ** operator:

dict_vec = {'x': 1, 'y': 0, 'z': 1}
myfunc(**dict_vec)
# Output: 1 0 1

Argument unpacking is a powerful feature that can simplify your code and make it more readable. So next time you find yourself with a tuple or a dictionary, give argument unpacking a try! 😎👍

9. Measure the execution time of small bits of Python code with the “timeit” module

🕰️ Time is of the essence, especially when it comes to writing efficient Python code. That’s where the “timeit” module comes in handy! With it, you can measure the execution time of small code snippets and optimize your code to run faster. Here’s an example:

Let’s say you want to join a range of numbers with a hyphen. You can use a for loop, a list comprehension, or the “map” function. But which one is faster? Let’s find out:

First, we import the “timeit” module:

import timeit

Next, we write three versions of the same code using a for loop, a list comprehension, and the “map” function. We pass each code snippet to the “timeit” function and specify the number of times we want to run it:

# Using a for loop
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

# Using a list comprehension
timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)

# Using the map function
timeit.timeit('"-".join(map(str, range(100)))', number=10000)

The “timeit” function returns the execution time in seconds. In this example, we see that using the “map” function is the fastest method, taking only 0.24 seconds to complete.

⚡️ By measuring the execution time of small code snippets with “timeit”, we can optimize our Python code to run faster and more efficiently.

10. “is” vs “==”

🐶 Let’s say we have a dog named “a”. 🐕

a = [1, 2, 3]

🐾 We also have another dog, “b”, that we want to be just like “a”. 🐾

b = a

🤝 If we check to see if “a” is “b”, we get True, because they are literally the same dog! 🤝

>>> a is b 
True

🧐 But if we just want to make sure they have the same qualities, like the same number of legs and a wagging tail, we would use “==” and get True as well. 🧐

>>> a == b 
True

👫 Now let’s say we have another dog “c”, who we want to be like “a”, but not actually the same dog. 🐕‍🦺

c = list(a)

🤝 If we use “==” to compare “a” and “c”, we still get True, because they have the same qualities. 🤝

>>> a == c 
True

🤔 But if we use “is”, we get False, because they are two separate dogs. 🤔

>>> a is c 
False
  • “is” expressions evaluate to True if two variables point to the same object
  • “==” evaluates to True if the objects referred to by the variables are equal

I hope this helps clarify the difference between “is” and “==”!

And there you have it, some snippets of Python code that showcase the beauty, simplicity, and versatility of this amazing programming language. Whether you’re a beginner or an experienced developer, these code examples can help you improve your coding skills and inspire you to write more Pythonic code. Remember, coding can be fun, and Python makes it even more enjoyable with its straightforward syntax and powerful features. So keep on coding, and may the Pythonic force be with you! 🐍💻

If you like what I am writing, give me a follow, share some of my stories.
You can follow me on GitHub and connect with me on Linkedin. You can also read about some more powerful Python one-liners here

--

--

Rishav Nath Pati

Game Developer | Unity | 2D,3D,AR/VR | C#>Python>JAVA>C++>C | ! an “ML Enthusiast” | Interactive Media Developer at Convai