Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an item from a "collections.defaultdict"?

Tags:

python

I have a collections.defaultdict as follows:

mydict = defaultdict(lambda:0)
mydict['stock1'] = 1.11
mydict['stock2'] = 2.22
mydict['stock3'] = 3.33

Now I want to remove the second item completely, how can I do that?

Maybe there is little seens to remove that but just simply set it to zero as follow:

mydict['stock2'] = 0
like image 606
thomas2004ch Avatar asked Jun 30 '16 12:06

thomas2004ch


People also ask

What is collections Defaultdict in Python?

A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.

Is Defaultdict faster than dict?

Finally, using a defaultdict to handle missing keys can be faster than using dict.

Does Defaultdict maintain order?

DefaultDict ,on append elements, maintain keys sorted in the order of addition [duplicate]

How does Defaultdict work Defaultdict forces a dictionary?

A defaultdict can be created by giving its declaration an argument that can have three values; list, set or int. According to the specified data type, the dictionary is created and when any key, that does not exist in the defaultdict is added or accessed, it is assigned a default value as opposed to giving a KeyError .


1 Answers

See the documentation, it's just like the ordinary dictionary. You can use either:

  • del mydict['stock2']
  • mydict.pop('stock2')
like image 108
unwind Avatar answered Sep 28 '22 01:09

unwind