deleting entries in a dictionary based on a condition

The usual way is to create a new dictionary containing only the items you want to keep:

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

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

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

Note that list(data.items()) creates a shallow copy of the items of the dictionary, i.e. a new list containing references to all keys and values, so it’s safe to modify the original dict inside the loop.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)