Home > Back-end >  How can I delete an element in list in a dictionary?
How can I delete an element in list in a dictionary?

Time:01-13

I was practicing my grip on dictionaries and then I came across this problem. I created a dictionary with a few keys and some keys have multiple values which were assigned using lists.

eg:

mypouch = {
    'writing_stationery': ['Pens', 'Pencils'],
    'gadgets': ['calculator', 'Watch'], 
    'Documents': ['ID Card', 'Hall Ticket'], 
    'Misc': ['Eraser', 'Sharpener', 'Sticky Notes']
}

I want to delete a specific item 'Eraser'.

Usually I can just use pop or del function but the element is in a list. I want the output for misc as 'Misc':['Sharpener', 'Sticky Notes'] What are the possible solutions for this kind of a problem?

CodePudding user response:

You can do:

mypouch['Misc'].remove('Eraser')

Or, use a set rather than a list:

for k in mypouch:
  mypouch[k] = set(mypouch[k])

then, it is easy and O(1) to remove an element in a set, using the same code as the list.

CodePudding user response:

Here is a 4 ways to do it the best is with remove but maybe you want to know different approaches

You can use filter

mypouch['Misc'] = list(filter(lambda x: x!='Eraser', mypouch['Misc']))

or short for with if

mypouch['Misc'] = [x for x in mypouch['Misc'] if x != 'Eraser']

or build-in function list remove

mypouch['Misc'].remove('Eraser')

or you can use pop and index combo

mypouch['Misc'].pop(mypouch['Misc'].index('Eraser'))
  • Related