Is Python's OrderedDict
data structure a mutable collection?
The documentation does not say anything about it, and after a quick search on the web, I have not found any answer yet.
CodePudding user response:
The documentation does not say anything about it, and after a quick search on the web, I have not found any answer yet.
When in doubt regarding mutability of class you might run following test
from collections import OrderedDict
from collections.abc import MutableSequence, MutableSet, MutableMapping
print(issubclass(OrderedDict,(MutableSequence,MutableSet,MutableMapping)))
output
True
See Collections Abstract Base Classes in collections.abc
docs for other things which can be checked this way.
CodePudding user response:
OrderedDict is mutable:
from collections import OrderedDict
d = OrderedDict.fromkeys('abcde')
d['a']= 'aretor'
print(d)
>> OrderedDict([('a', 'aretor'), ('b', None), ('c', None), ('d', None), ('e', None)])
print(d['a'])
>> aretor
CodePudding user response:
From realpython.com:
Since OrderedDict is a mutable data structure, you can perform mutating operations on its instances. You can insert new items, update and remove existing items, and so on. If you insert a new item into an existing ordered dictionary, then the item is added to the end of the dictionary:
They provide a couple of examples for mutable operations like insert:
>>> from collections import OrderedDict
>>> numbers = OrderedDict(one=1, two=2, three=3)
>>> numbers
OrderedDict([('one', 1), ('two', 2), ('three', 3)])
>>> numbers["four"] = 4
>>> numbers
OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)])
Generally, if a datatype supports the following operations, then it is considered a mutable sequence type.