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 OverflowConstructing 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]
Slightly more elegant dict comprehension:
foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}
How to filter dictionary by value?
How to filter through a dictionary returning a list of key objects?
How to filter dictionary keys by substring in Python? - Ask a Question - TestMu AI (formerly LambdaTest) Community
Filtering Dictionaries by Key and Key/Value
Videos
If I have a dictionary of students (key) and their averages (value), how can I create a function to help me return only the students with averages above 90?
So let's say I have a dictionary of
dict = { chevy_01 : "Ford", chevy_02: "Tahoe"}
I want to filter through the KEYS of the dict and get the last two characters of the keys while later performing another function. So I imagine something like this
{for keys in vals print (key[-2:]}
But I want the end of the function to return a list of the last two characters in the dict so it will just return [01, 02].
I want to do this in a lambda function I'm bad at dict comprehension. Can someone help me out?