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}

dict = {'Name': 'Dinesh',
        'Marks': [62, 54, 83],
        1: 'Maths',
        2:'Physics',
        3:'Chemistry'}

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)

from collections import OrderedDict

#creating an ordered dictionary from a regular dictionary
dict = {1: 'A', 5: 'E', 2: 'B', 0: 'Z', 4: 'D', 3: 'C'}
ord_dict1 = OrderedDict(dict)
print(ord_dict1)
#Output: OrderedDict([(1, 'A'), (5, 'E'), (2, 'B'), (0, 'Z'), (4, 'D'), (3, 'C')])

#creating an empty ordered dictionary
ord_dict2 = OrderedDict() 
print(ord_dict2)
#Output: OrderedDict()

#adding elements in an ordered dictionary
ord_dict2['a'] = 0
ord_dict2['b'] = 1
ord_dict2['c'] = 2
ord_dict2['d'] = 3
ord_dict2['e'] = 4
print(ord_dict2) 
#Output: OrderedDict([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4)])

ord_dict1['F'] = 6
ord_dict1[7] = 'G'
print(ord_dict1)
#Output: OrderedDict([(1, 'A'), (5, 'E'), (2, 'B'), (0, 'Z'), (4, 'D'), (3, 'C'), ('F', 6), (7, 'G')])

#overwriting an Ordered Dictionary key value
ord_dict1[0] = 0
print(ord_dict1)
#Output: OrderedDict([(1, 'A'), (5, 'E'), (2, 'B'), (0, 0), (4, 'D'), (3, 'C'), ('F', 6), (7, 'G')])
#If a new key overwrites an existing key, the original insertion position is left unchanged

#pop last key value pair from an Ordered Dictionary
ord_dict2.popitem()
print(ord_dict2)
#Output: OrderedDict([('a', 0), ('b', 1), ('c', 2), ('d', 3)])

#removing a key value pair from an Ordered Dictionary
ord_dict1.pop(4)
print(ord_dict2)
#Output: OrderedDict([(1, 'A'), (5, 'E'), (2, 'B'), (0, 0), (3, 'C'), ('F', 6), (7, 'G')])
 
#reinserting key value pair in the Ordered Dictionary
ord_dict1[4] = 'D'
print(ord_dict1)
#Output: OrderedDict([(1, 'A'), (5, 'E'), (2, 'B'), (0, 0), (3, 'C'), ('F', 6), (7, 'G'), (4, 'D')])
#Deleting a key and reinserting it will move it to the end of the Ordered Dictionary

#equality tests of regular dictionaries and Ordered Dictionaries
dict1 = {1: 'A', 5: 'E', 2: 'B', 0: 0, 3: 'C', 'F': 6, 7: 'G', 4: 'D'}
dict2 = {1: 'A', 5: 'E', 2: 'B', 0: 0, 4: 'D', 3: 'C', 'F': 6, 7: 'G'}
ord_dict1 = OrderedDict(dict1)
ord_dict2 = OrderedDict(dict2)
print(dict1 == dict2)
#Output: True

print(ord_dict1 == ord_dict2)
#Output: False

print(dict1 == ord_dict1)
#Output: True

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.

from collections import defaultdict 

d_dict1 = defaultdict(lambda: None) #default value is None
d_dict1['Zero']
print(d_dict1)
#Output: defaultdict(<function  at 0x7f9f464ccdc0>, {'Zero': None})

print(d_dict1.items())
#Output: dict_items([('Zero', None)])

print(dict(d_dict1))
#Output: {'Zero': None}

d_dict1[1] = 'One'
d_dict1['Two'] = 2
d_dict1[3]
d_dict1[4]
d_dict1['Five'] = 5
print(dict(d_dict1))
#Output: {'Zero': None, 1: 'One', 'Two': 2, 3: None, 4: None, 'Five': 5}

#using int as default factory
d_dict2 = defaultdict(int) #default value is 0
d_dict2[1] = 'One'
d_dict2['Two'] = 2
d_dict2[3]
print(dict(d_dict2))
#Output: {1: 'One', 'Two': 2, 3: 0}

print(d_dict2[0])
#Output: 0

print(dict(d_dict2))
#Output: {1: 'One', 'Two': 2, 3: 0, 0: 0}

#using string as default factory 
d_dict3 = defaultdict(str) #default value is ''
d_dict3[1] = 'One'
d_dict3['Two'] = 2
d_dict3[3]
print(dict(d_dict3))
#Output: {1: 'One', 'Two': 2, 3: ''}

#using float as default factory 
d_dict4 = defaultdict(float) #default value is 0.0
d_dict4[1] = 'One'
d_dict4['Two'] = 2
d_dict4[3]
print(dict(d_dict4))
#Output: {1: 'One', 'Two': 2, 3: 0.0}

#using list as default factory 
d_dict5 = defaultdict(list) #default value is []
d_dict5[1] = 'One'
d_dict5['Two'] = 2
d_dict5[3]
print(dict(d_dict5))
#Output: {1: 'One', 'Two': 2, 3: []}

#using tuple as default factory 
d_dict6 = defaultdict(tuple) #default value is ()
d_dict6[1] = 'One'
d_dict6['Two'] = 2
d_dict6[3]
print(dict(d_dict6))
#Output: {1: 'One', 'Two': 2, 3: ()}

#using set as default factory 
d_dict7 = defaultdict(set) #default value is set() #As python seizes an empty curly braces {} as an empty dictionary, an empty set is denoted by set()
d_dict7[1] = 'One'
d_dict7['Two'] = 2
d_dict7[3]
print(dict(d_dict7))
#Output: {1: 'One', 'Two': 2, 3: set()}

#using dictionary as default factory 
d_dict8 = defaultdict(dict) #default value is {}
d_dict8[1] = 'One'
d_dict8['Two'] = 2
d_dict8[3]
print(dict(d_dict8))
#Output: {1: 'One', 'Two': 2, 3: {}}

#using custom value as default factory 
d_dict9 = defaultdict(lambda: 100) #default value is 100
d_dict9[1] = 'One'
d_dict9['Two'] = 2
d_dict9[3]
print(dict(d_dict9))
#Output: {1: 'One', 'Two': 2, 3: 100}

Related Posts-

Leave a Comment

%d bloggers like this: