![]() |
|
[Tut] Python Print Dictionary Without One Key or Multiple Keys - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Print Dictionary Without One Key or Multiple Keys (/thread-100057.html) |
[Tut] Python Print Dictionary Without One Key or Multiple Keys - xSicKxBot - 10-10-2022 Python Print Dictionary Without One Key or Multiple Keys 5/5 – (1 vote) 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 Code: print()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 PythonMethod 1: Dictionary Comprehension ![]() Say, you have one or more keys stored in a variable Code: ignore_keysCreate a filtered dictionary without one or multiple keys using the dictionary comprehension Code: {k:v for k,v in my_dict.items() if k not in ignore_keys}Here’s a minimal example: Code: 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}
print(filtered_dict)
# {'z': 3}The Code: dict.items()The membership operator Code: k not in ignore_keys The runtime complexity of the membership check is constant O(1) if you use a set for the Code: ignore_keysNote 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 PythonMethod 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 Code: forCode: ifHere’s an example using three lines and directly printing the key-value pairs: Code: 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: Code: z 3Of course, you can modify the output to your own needs. See the customizations of the built-in Code: print() Recommended Tutorial: Python Code: print()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 Code: exclude_keysI 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 Code: forThat’s it.
|