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 Overflowpython - Filter dict to contain only certain keys? - Stack Overflow
python - Filter a dictionary based on a constraint on the keys in a Pythonic way - Stack Overflow
filter items in a python dictionary where keys contain a specific string - Stack Overflow
Filtering dictionary in python - Stack Overflow
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]
Slightly more elegant dict comprehension:
foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}
How about this:
In Python 3.x :
def slicedict(d, s):
return {k:v for k,v in d.items() if k.startswith(s)}
in Python 2.x :
def slicedict(d, s):
return {k:v for k,v in d.iteritems() if k.startswith(s)}
In functional style:
dict(filter(lambda item: item[0].startswith(string),sourcedict.iteritems()))
How about a dict comprehension:
filtered_dict = {k: v for k, v in d.iteritems() if filter_string in k}
One you see it, it should be self-explanatory, as it reads like English pretty well.
This syntax requires Python 2.7 or greater.
In Python 3, there is only dict.items(), not iteritems() so you would use:
filtered_dict = {k: v for k, v in d.items() if filter_string in k}
You can use the built-in filter function to filter dictionaries, lists, etc. based on specific conditions.
filtered_dict = dict(
filter(lambda item: filter_str in item[0], d.items())
)
The advantage is that you can use it for different data structures.
You can't do such directly with dict[keyword]. You have to iterate through the dict and match each key against the keyword and return the corresponding value if the keyword is found.
This is going to be an O(N) operation.
>>> my_dict = {'name': 'Klauss', 'age': 26, 'Date of birth': '15th july'}
>>> next(v for k,v in my_dict.items() if 'Date' in k)
'15th july'
To get all such values use a list comprehension:
>>> [ v for k, v in my_dict.items() if 'Date' in k]
['15th july']
use str.startswith if you want only those values whose keys starts with 'Date':
>>> next( v for k, v in my_dict.items() if k.startswith('Date'))
'15th july'
>>> [ v for k, v in my_dict.items() if k.startswith('Date')]
['15th july']
not the best solution, can be improved (overide getitem)
class mydict(dict):
def __getitem__(self, value):
keys = [k for k in self.keys() if value in k]
key = keys[0] if keys else None
return self.get(key)
my_dict = mydict({'name': 'Klauss', 'age': 26, 'Date of birth': '15th july'})
print(my_dict['Date'])# returns 15th july