for key, value in your_dict.items():
    if key not in your_blacklisted_set:
        print value

the beauty is that this pseudocode example is valid python code.

it can also be expressed as a list comprehension:

resultset = [value for key, value in your_dict.items() if key not in your_blacklisted_set]
Answer from Samus_ on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ how do you print keys and values of a dictionary except one of the keys? (python)
r/learnprogramming on Reddit: How do you print keys and values of a dictionary except one of the keys? (Python)
July 23, 2023 -

First of all, Im a beginner, so please explain it simple.

for example we have a dictionary of keys like username and password and gmail and some values, I want to print all the keys and values except password key. so what should I write?

I've tried this but it won't work.

information = {
     "Username" : "Guest",
     "Password" : "Guest1234",
     "Gmail" : "Guest1234@gmail.com",
     "Gender" : "Unknown",
     "Phone" : 123456789
}

for x,y in information.items():
    print(x,y except "Password")

Discussions

Copy a dictionary, except some keys - Ideas - Discussions on Python.org
How common is the need of getting a copy of a dict, except some of its keys? It happens to me quite frequently that I need a similar dict to what I have, but without some of its keys. Of course I canโ€™t just remove the keys, as other parts of the code still uses the full dict. More on discuss.python.org
๐ŸŒ discuss.python.org
1
October 31, 2019
python - Return copy of dictionary excluding specified keys - Stack Overflow
I want to make a function that returns a copy of a dictionary excluding keys specified in a list. ... I would like to do this in a one-line with a neat dictionary comprehension but I'm having trouble. More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - delete all keys except one in dictionary - Stack Overflow
What I want to do is to delete all the keys except one key. Suppose I want to save only en here. How can I do it ? (pythonic solution) What I have tried: In [18]: for k in lang: ....: if k != 'en': ....: del lang_name[k] .... Which gave me the run time error:RuntimeError: dictionary changed ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Is it possible to iterate through all of a dictionary's keys except a specific subset? - Stack Overflow
Let's say I have a dictionary with the keys being all the numbers 1-10. And I want to iterate through that excluding keys 6-8. Is it possible to do something like for key in dictionary.keys().exclu... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 1
4

Your code is pretty good, there is one thing that I would add, the for-else keyword, as this gets rid of the found variable. Which honestly is just noise. This is as if a for loop runs completely without breaking then the else will run too. But if it breaks then it won't run the else. This can leave you with:

def group_by_excluding_key(list_of_dicts, key_field):
    """
    Takes a list of `dict` items and groups by ALL KEYS in the dict EXCEPT the key_field.
    :param list_of_dicts: List of dicts to group
    :param key_field: key field in dict which should be excluded from the grouping
    """
    output = []
    for item in list_of_dicts:
        item_key = item.pop(key_field)
        for existing_group, found_keys in output:
            if existing_group.viewitems() == item.viewitems():
                found_keys.append(item_key)
                break
        else:
            output.append((item, [item_key]))
    return output

Other than that your code is good.


But if I were to were to write this, I'd prefer a very small solution. Lets say dicts are hash able, what you want is a dictionary that has the modified item as the key, and the popped item_key as the value. This obviously has two down-sides, it's not ordered, and dicts aren't hash able. Both easily solved with collections.OrderedDict and tuple(dict.items()). And so can result in:

from collections import OrderedDict

def group_by_excluding_key(list_of_dicts, key_field):
    """
    Takes a list of `dict` items and groups by ALL KEYS in the dict EXCEPT the key_field.
    :param list_of_dicts: List of dicts to group
    :param key_field: key field in dict which should be excluded from the grouping
    """
    output = OrderedDict()
    for item in list_of_dicts:
        key = item.pop(key_field)
        output.setdefault(tuple(item.items()), []).append(key)
    return [(dict(key), value) for key, value in output.items()]

This has the benefit of moving the for loop into the OrderedDict, and possibly getting \ key lookup, but requires you to change the type of all the keys, twice.

I know you didn't ask for a performance review, but the performance difference between my code and your code can be tested with the following. The comments are my functions run time over yours as a percentage, so if mine took 0.8s and yours 3.3s then it'll be 24%, followed by how long it took my function to run.

from timeit import timeit
from itertools import count

# 240%, 0.1s
c = count(1)
l = [{'status': 1, 'product': i, 'id': next(c)} for i in range(10)]
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=1000))
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key as fn', number=1000))

# 25%, 0.8s
c = count(1)
l = [{'status': 1, 'product': i, 'id': next(c)} for i in range(100)]
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=1000))
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key as fn', number=1000))

# 28%, 0.8s
c = count(1)
l = [{'status': i, 'product': j, 'id': next(c)} for i in range(10) for j in range(10)]
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=1000))
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key as fn', number=1000))

# 0.4%, 0.9s
c = count(1)
l = [{'status': i, 'product': j, 'id': next(c)} for i in range(100) for j in range(100)]
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=10))
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key as fn', number=10))
๐ŸŒ
Finxter
blog.finxter.com โ€บ python-print-dictionary-without-one-key-or-multiple-keys
Python Print Dictionary Without One or Multiple Key(s) โ€“ Be on the Right Side of Change
October 9, 2022 - ๐Ÿ‘‰ Recommended Tutorial: How to Filter a Dictionary in Python ยท 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.
๐ŸŒ
Python.org
discuss.python.org โ€บ ideas
Copy a dictionary, except some keys - Ideas - Discussions on Python.org
October 31, 2019 - How common is the need of getting a copy of a dict, except some of its keys? It happens to me quite frequently that I need a similar dict to what I have, but without some of its keys. Of course I canโ€™t just remove the kโ€ฆ
๐ŸŒ
Python Guides
pythonguides.com โ€บ copy-a-python-dictionary-without-some-of-its-keys
How to Copy a Python Dictionary Without One Key
September 10, 2025 - Here, the comprehension loops through all key-value pairs and excludes the one with the โ€œsalaryโ€ key. I like this method because itโ€™s concise and doesnโ€™t modify the original dictionary. Itโ€™s also very flexible; you can exclude multiple keys by adding them to a set. Sometimes, I prefer using Pythonโ€™s built-in copy() method along with pop().
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-extract-specific-keys-from-dictionary
Python | Extract specific keys from dictionary - GeeksforGeeks
July 27, 2023 - We have a lot of variations and applications of dictionary containers in Python and sometimes, we wish to perform a filter of keys in a dictionary, i.e extracting just the keys which are present in the particular container.
Find elsewhere
๐ŸŒ
Powerfulpython
powerfulpython.com โ€บ blog โ€บ checking-dict-keys
Checking Python Dict Keys Is Simple. Right?
That brings us to the third approach: the dict.get() method. This fetches the value if the key is present, or an alternate value if not - all without raising any exception. You can call it with two arguments - the key, and the default value: ...
๐ŸŒ
Quora
quora.com โ€บ How-do-I-fetch-only-few-values-from-a-Python-dictionary-and-get-only-those-keys
How to fetch only few values from a Python dictionary and get only those keys - Quora
Answer (1 of 2): There are several ways you could do this. But you must note that fetching through values might retrieve multiple keys if they have the same value. One simple way to do this in a single line pythonic way is to use list comprehensions as below: [code]mydict = {key1: value1, key2: ...
๐ŸŒ
Python.org
discuss.python.org โ€บ ideas
Copy a dictionary, except some keys - #6 by mjpieters - Ideas - Discussions on Python.org
November 1, 2019 - How common is the need of getting a copy of a dict, except some of its keys? It happens to me quite frequently that I need a similar dict to what I have, but without some of its keys. Of course I canโ€™t just remove the kโ€ฆ
๐ŸŒ
sprig
masterminds.github.io โ€บ sprig โ€บ dicts.html
Dictionaries and Dict Functions | sprig
Use the uniq function along with sortAlpha to get a unqiue, sorted list of keys. ... The pick function selects just the given keys out of a dictionary, creating a new dict. ... The omit function is similar to pick, except it returns a new dict with all the keys that do not match the given keys.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-remove-multiple-keys-from-dictionary
Python - Remove Multiple Keys from Dictionary - GeeksforGeeks
January 29, 2025 - A conditional check ensures the key exists before deletion to avoid errors.. filter() function combined with a lambda function can create a new dictionary excluding the specified keys.
๐ŸŒ
OneUptime
oneuptime.com โ€บ home โ€บ blog โ€บ how to check if key exists in dictionary in python
How to Check if Key Exists in Dictionary in Python
January 25, 2026 - Dictionary key lookup is O(1) on average. import timeit data = {str(i): i for i in range(10000)} # All these are effectively O(1) and very fast # 'in' operator t1 = timeit.timeit(lambda: '5000' in data, number=100000) # get() method t2 = timeit.timeit(lambda: data.get('5000'), number=100000) # try/except (when key exists) def try_access(): try: return data['5000'] except KeyError: return None t3 = timeit.timeit(try_access, number=100000) print(f"'in' operator: {t1:.4f}s") print(f"get() method: {t2:.4f}s") print(f"try/except: {t3:.4f}s") # All are very fast, differences are negligible for most uses
๐ŸŒ
Google
developers.google.com โ€บ google for education โ€บ python โ€บ python dict and file
Python Dict and File | Python Education | Google for Developers
Looking up a value which is not in the dict throws a KeyError -- use "in" to check if the key is in the dict, or use dict.get(key) which returns the value or None if the key is not present (or get(key, not-found) allows you to specify what value ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dictionaries_access.asp
Python - Access Dictionary Items
Python Examples Python Compiler ... ยป ยท There is also a method called get() that will give you the same result: ... The keys() method will return a list of all the keys in the dictionary....