Constructing a new dict:

dict_you_want = {key: old_dict[key] for key in your_keys}

Uses dictionary comprehension.

If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((key, old_dict[key]) for ...). It's the same, though uglier.

Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.

Removing everything in-place:

unwanted = set(old_dict) - set(your_keys)
for unwanted_key in unwanted: del your_dict[unwanted_key]
Answer from user395760 on Stack Overflow
๐ŸŒ
Mark Needham
markhneedham.com โ€บ blog โ€บ 2020 โ€บ 04 โ€บ 27 โ€บ python-select-keys-from-map-dictionary
Python: Select keys from map/dictionary | Mark Needham
April 27, 2020 - But what if we want to return the values as well? This is where dictionary comprehensions come in handy. We can tweak our code as follows: >>> {key: x[key] for key in ["a", "b"]} {'a': 1, 'b': 2}
Discussions

Pick a key from a dictionary python - Stack Overflow
go through a dictionary picking keys from it in a loop? For example lets say I have the following dictionary: {'hello':'world', 'hi':'there'}. Is there a way to for loop through the dictionary and... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to select keys from a dictionary by their order? - Stack Overflow
Sorry this is probably very simple, but I suspect I'm wording the question wrong from inexperience so I haven't been able to find the answer anywhere. I have a dictionary, e.g.: dict = {1: 'a', 2:... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to select only specific key-value pairs from a list of dictionaries? - Stack Overflow
0 Selecting objects with specific key:value pair from dictionary ยท 1 Python: select key, values from dictionary corresponding to given list More on stackoverflow.com
๐ŸŒ stackoverflow.com
Select the key:value pairs from a dictionary in Python - Stack Overflow
This wouldn't take any extra space, ... required from old to new dict, and would solve the problem of slow selective popping as well(as we're not traversing through all but only the selective one's which are required). ... Since my dictionary a is too large and b is small. I remove most of the keys... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to select certain key from dictionary, based on value?
r/learnpython on Reddit: How to select certain key from dictionary, based on value?
November 10, 2021 -

I have the following dictionary that contains 5 keys.

dic1={'key1': ['test1', 99.172, 0.456], 'key2': ['test2', 99.473, 0.366], 'key3': ['test3', 99.278, 0.583], 'key4': ['test4', 99.773, 0.207], "key5":['test5', 92.172, 0.486]}

My question is:

How do I select the key from the dictionary where the 3rd value, is closest to 0.5 ?

in this case the result should be

result={"key5":['test5', 92.172, 0.486]}

๐ŸŒ
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.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-extract-specific-keys-from-dictionary
Python Extract specific keys from dictionary?
Python provides several approaches to accomplish this task efficiently. This approach uses dictionary comprehension with set intersection to filter keys. The & operator finds common keys between the dictionary keys and your desired keys ? schedule = {'Sun': '2 PM', 'Tue': '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'} # Given dictionary print("Given dictionary:", schedule) # Extract specific keys using set intersection desired_keys = {'Fri', 'Sun'} result = {key: schedule[key] for key in schedule.keys() & desired_keys} # Result print("Dictionary with given keys:", result)
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Get Keys from a Dictionary by Value in Python | note.nkmk.me
May 19, 2025 - def get_keys_from_value(d, val): return [k for k, v in d.items() if v == val] keys = get_keys_from_value(d, 'aaa') print(keys) # ['key1', 'key2'] ... The following version is suitable for dictionaries without duplicate values.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-selective-key-values-in-dictionary
Python | Selective key values in dictionary | GeeksforGeeks
April 27, 2023 - # Python3 code to demonstrate working of # Selective key values in dictionary # Using the operator module # Import the operator module import operator # Initialize dictionary test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5} # printing original dictionary print("The original dictionary : " + str(test_dict)) # Initialize key list key_list = ['gfg', 'best', 'CS'] # Selective key values in dictionary using the operator module res = list(map(operator.itemgetter(*key_list), [test_dict])) # printing result print("The values of Selective keys : " + str(res))
Find elsewhere
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-dictionary-multiple-keys
How To Select Multiple Keys From A Dictionary In Python?
March 18, 2025 - Read How to Convert a Dictionary to a List in Python? One of the best methods for selecting multiple keys from a dictionary is by using the Dictionary comprehension approach.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dictionaries_access.asp
Python - Access Dictionary Items
The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list. Add a new item to the original dictionary, and see that the keys list gets updated as well:
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-get-dictionary-keys-as-a-list
Dictionary keys as a list in Python - GeeksforGeeks
Sometimes, you might want to change a dictionary into a list, and Python offers various ways to do this. How to Convert a Dict ... We are given a dictionary and our task is to print its keys, this can be helpful when we want to access or display only the key part of each key-value pair.
Published ย  January 6, 2025
๐ŸŒ
Quora
quora.com โ€บ Is-there-a-way-to-extract-specific-keys-and-values-from-an-ordered-dictionary-in-Python
Is there a way to extract specific keys and values from an ordered dictionary in Python? - Quora
Answer (1 of 6): you can use the get( ) or indexing (similar to arrays) or values( ) to obtain values. to obtain keys you can use keys( ) and if you want to obtain specific keys , you can use items( ) on dict. object to obtain key value pair and then enumerate over it based on some condition to ...
Top answer
1 of 4
1

I think you're misunderstanding what filter() does. From the docs:

filter(function, iterable):
Construct an iterator from those elements of iterable for which function returns true.

So when you do

hits = dict(filter(lambda item: 'hit' in item[0], topHitsDict['record301'].items()))

You're essentially doing:

hits = {}
for item in topHitsDict['record301'].items():
    if 'hit' in item[0]:
        hits[item[0]] = item[1]

which gives you only the hit* keys from topHitsDict['record301'].

hits = {'hit1': {'description': 'OBGP-2018-240_Oncorhynchus.clarkii',
  'score': '340',
  'eval': '2e-94'},
 'hit2': {'description': 'OBGP-2017-332_Oncorhynchus.clarkii',
  'score': '340',
  'eval': '2e-94'}}

Instead, what you actually want is the description from those hit* dicts. For this, you can use map, and then convert the iterator to a list.

descriptions = list(map(lambda item: item[1]['description'], hits.items())
# descriptions: ['OBGP-2018-240_Oncorhynchus.clarkii', 'OBGP-2017-332_Oncorhynchus.clarkii']

This is equivalent to:

descriptions = []
for item in hits.items():
    descriptions.append(item[1]['description'])

And if you want to do this for all keys of topHitsDict, you'd have to change it up a bit. Either using a loop:

all_descriptions = []
for recordVal in topHitsDict.values():
    hits = dict(filter(lambda item: 'hit' in item[0], recordVal.items()))
    descriptions = list(map(lambda item: item[1]['description'], hits.items())
    # Add to all_descriptions
    all_descriptions = all_descriptions + descriptions

It's almost always easier to write these out as a loop first. Then you can write them as a list- or dict- comprehension, and then use filter() and map()

all_descriptions = []

for record in topHitsDict.values():
    for hitname, hitval in record.items():
        if "hit" in hitname:
            all_descriptions.append(hitval['description'])

Or as a comprehension:

all_descriptions = [hitval["description"] for record in topHitsDict.values() for hitname, hitval in record.items() if "hit" in hitname]
2 of 4
0

You will require 2 loops to complete this unless you insist on processing every recordxxx key separately using 1 loop.
And also list comprehensions are a little bit easier to read/understand than filter.

desc = [
    v["description"]
    for _, value in topHitsDict.items()
    for k, v in value.items()
    if "hit" in k
]
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ standard-library โ€บ dict โ€บ keys
Python dict keys() - Retrieve Dictionary Keys | Vultr Docs
November 11, 2024 - Obtain the keys from a dictionary using keys(). Use the list() function to convert the keys to a list.