What is Ordered Dictionary and Default Dictionary in Python?


Dictionary in Python

Dictionary is an unordered collection of mutable values indexed by unique keys. Values in a dictionary can be of any datatype, mutable and can be duplicated, whereas keys can’t be repeated and are immutable. Dictionaries are just like map(), storing, and retrieving
elements by referencing a key. As dictionaries are referenced by key, they have very fast lookups. The syntax of a dictionary is as follows:

Dictionary_name = { key:  value}

Ordered Dictionary in Python

An Ordered Dictionary is a dictionary subclass that preserves the order in which the keys are inserted. A regular dictionary doesn’t track the insertion order, and iterating over it returns the elements in an arbitrary order. On contradiction, an Ordered Dictionary tracks the insertion order, and iterating over it returns the elements in the order they were inserted. OrderedDict is part of the Python collections module. The syntax of an Ordered Dictionary is as follows:

OrderedDict(Regular Dictionary)

Default Dictionary in Python

When a key is not present in a dictionary, it raises a KeyError that might become a problem. To overcome this Python introduces another dictionary like container known as Defaultdict that is present inside the collections module. Defaultdict is a sub-class of the dict class that works exactly like a normal dictionary, but it is initialized with a function that takes no arguments and returns the default value to a key that does not exist. Thus it never raises a KeyError.

defaultdict(default_factory)

  • default_factory: A function that takes no arguments and returns the default value for the dictionary keys. If this argument is absent then the dictionary raises a KeyError.

If the key is not present in the Default Dictionary while accessing it, it will create the key and automatically assigns the default value to the key. The Default Dictionary can have multiple built-in types as default values for keys.

Related Posts-

Add Comment

%d bloggers like this: