1

This probably a very basic question but having difficulty search for the correct answer. I have a Python dictionary named raw_data and am extracting the keys separately as follows:

features = raw_data.keys()

A few specific elements of the keys need to be deleted.

del features[137]
del features[160]
del features[181]

The above code however throws an error:

'dict_keys' object doesn't support item deletion

What is the correct way to delete a key form dictionary keys object?

martineau
  • 119,623
  • 25
  • 170
  • 301
Ravi
  • 3,223
  • 7
  • 37
  • 49

1 Answers1

2

'dict_keys' is a view-object.

It provides dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects

Hence it does not make sense to delete keys in the view without changing the dictionary itself. To delete the keys in the dictionary itself, see @ailin's answer. Following the deletion of keys in the dictionary, the keys will also be deleted in your dict_keys-view object.

If, however, you simply want a list with relevant keys, you can either convert the dict_keys object to a list and filter, or iterate over your dict_keys-object directly and filter the ones you do not need.

relevant_keys = [x for x in features if x not in [137, 160, 181]]
tomanizer
  • 851
  • 6
  • 16