Delete entries in a dictionary based on a condition

I have a dictionary with names as a key and (age, date of birth) tuple as a value for these keys. For example.

dict = {'Adam' : (10, '2002-08-13'), 'Eve' : (40, '1972-08-13')} 

I want to delete all keys with an age> 30 for their age in a set of values, how can I do this? I am looking for the age of each key using dict[name][0] , where dict is my dictionary.

+8
python dictionary
source share
1 answer

The usual way is to create a new dictionary containing only those elements that you want to save:

 new_data = {k: v for k, v in data.iteritems() if v[0] <= 30} 

In Python 3.x, use items() instead of iteritems() .

If you need to change the source dictionary in place, you can use for -loop:

 for k, v in data.items(): if v[0] > 30: del data[k] 

In Python 3.x, use list(data.items()) instead of data.items() .

+21
source share

All Articles