Python Print Dictionary Without One or Multiple Key(s)

5/5 - (2 votes)

The most Pythonic way to print a dictionary except for one or multiple keys is to filter it using dictionary comprehension and pass the filtered dictionary into the print() function.

There are multiple ways to accomplish this and I’ll show you the best ones in this tutorial. Let’s get started! 🚀

👉 Recommended Tutorial: How to Filter a Dictionary in Python

Method 1: Dictionary Comprehension

Say, you have one or more keys stored in a variable ignore_keys that may be a list or a set for efficiency reasons.

Create a filtered dictionary without one or multiple keys using the dictionary comprehension {k:v for k,v in my_dict.items() if k not in ignore_keys} that iterates over the original dictionary’s key-value pairs and confirms for each key that it doesn’t belong to the ones that should be ignored.

Here’s a minimal example:

ignore_keys = {'x', 'y'}
my_dict = {'x': 1, 'y': 2, 'z': 3}

filtered_dict = {k:v for k,v in my_dict.items() if k not in ignore_keys}
# {'z': 3}

The dict.items() method creates an iterable of key-value pairs over which we can iterate.

The membership operator k not in ignore_keys tests if a given key doesn’t belong to the set.

💡 The runtime complexity of the membership check is constant O(1) if you use a set for the ignore_keys data structure. It would be linear O(n) in the number of elements if you used a list which is not a good idea for that reason.

Note that you can also use this approach to print a dictionary except a single key by putting only one key into the ignore list.

👉 Recommended Tutorial: Dictionary Comprehension in Python

Method 2: Simple For Loop with If Condition

A not-so-Pythonic but reasonably readable way to print a dict without one or multiple keys is to use a simple for loop with if condition to avoid all keys in the ignore list.

Here’s an example using three lines and directly printing the key-value pairs:

ignore_keys = {'x', 'y'}
my_dict = {'x': 1, 'y': 2, 'z': 3}

for k, v in my_dict.items():
    if k not in ignore_keys:
        print(k, v)

The output:

z 3

Of course, you can modify the output to your own needs. See the customizations of the built-in print() function and its awesome arguments:

👉 Recommended Tutorial: Python print() and Separator and End Arguments

My Recommendation – Use This Method!

I could have listed many more ways to solve this problem of printing a dict except one or more keys.

I have seen super inefficient ways proposed on forums that use exclude_keys that are list types.

I have also seen elaborate schemes to use set difference operations or more.

But I don’t recommend anything else than dict comprehension if you want to create a filtered dictionary object first and the simple for loop if you want to print on the fly.

That’s it. 👌