Home > Net >  Removing an element from a dictionary without deleting the index
Removing an element from a dictionary without deleting the index

Time:10-13

This is pretty basic but I'm fairly new to python and need some help. I have a set of class objects stored in a dictionary:

dict = {'1':object(1),object(2),object(3), '2':object(4),object(5),object(6), '3':object(7),object(8),object(9)}

I was curious how I would go about removing a single object from a given index. For instance, say I wanted to remove object(1) from '1' but keep object(2) and object(3). Any ideas? Thank you.

CodePudding user response:

assuming object(1), object(2), object(3) is stored as a list, you could just set the value equal to itself after skipping the first value. with dict comprehension:

dict2 = {k:v[1:] for k,v in dict.items()}

CodePudding user response:

Your dict element value is actually a list, so you can manipulate it as a list.

dict['1'].pop()
  • Related