Python Data Structures

Python Data Structure Series: Dictionary

Dictionaries are one of the most flexible built-in data types in Python. It’s Mutable Object, whose values can be changed at run time.

Dictionaries are unordered collections of items. It is different from list/tuple as items are stored and fetched by key instead of by positional offset.

Dictionary has a key: value pair.

Dictionaries take the place of records, search tables where item names are more meaningful than item positions.

Properties of Dictionary:

Accessed by key: Dictionaries are also called as Associative Arrays or Hashes. They associate a set of values with keys, by which you can fetch an item out of a dictionary using the key under which value has been stored.

Unordered collections: Unlike in Tuple or List, items stored in Dictionary are not kept in a Particular Order. Python pseudo-randomizes their left-to-right order to provide the faster lookup. Keys provide the symbolic (not physical) locations of items in a Dictionary.

Variable-length, heterogeneous type and nestable: Dictionaries can grow and shrink in a place. Values can contain objects of any type and supports the nesting behavior to any depth. Every Key has only one Associated Value.

Hash Tables: Internally Dictionaries are implemented as Hash Tables, which start small and can grow on demand. Python also employs optimized Hashing Algo to find the keys, to make retrieval faster. Just like the Lists, Dictionaries store object references.

Keys should be Immutable: Dictionaries uses a Hash Value calculated from the Key value to find the Key. If the key were a mutable object, its value could change, and thus its hash could also be changed. So when you try to look up the same object in the dictionary it won’t be found because its Hash Value is different.

Create a Dictionary:

Dictionary is written as series of key:value pair, separated by commas, enclosed in Curly Braces.

Below are some ways by which you can define a Dictionary

# empty dictionary 
my_dictionary = {}

# my dictionary with Integer Keys

my_dictionary = {1: 'One', 2: 'Two'}

# my dictionary with Mixed Keys

my_dictionary = {'name': 'Anurag', 1: 'One'}

#  create dictionary using dict()

my_dictionary = dict({1: 'One', 2: 'Two'})

# create dictionary from sequence having each item as a Pair

my_dictionary =dict([(1, 'One'), (2, 'Two')])

 

Some common operations on Dictionary:

# Alternative Dictionary Construction Method

my_dictionary = dict(name='Anurag', age=20)

# Using ZIP function on Keys list and values list 

keys_li = [1, 2, 3]
values_li = ['One', 'Two', 'Three']

my_dictionary = dict(zip(keys_li, values_li))  # {1: 'One', 2: 'Two', 3: 'Three'}


# create dictionary with null values 

my_dictionary = dict.fromkeys(['name', 'age'])

>> {'name': None, 'age': None}


# Operations on Dictionary 

In [3]: my_dictionary
Out[3]: {1: 'One', 'name': 'Anurag'}


# Fetch value using Key

In [4]: my_dictionary['name']
Out[4]: 'Anurag'

# Check whether Key exists or not.


In [6]: 1 in my_dictionary
Out[6]: True


# Fetch all the Keys of a Dictionary

In [7]: my_dictionary.keys()
Out[7]: [1, 'name']


# Fetch all the Values from a Dictionary

In [8]: my_dictionary.values()
Out[8]: ['One', 'Anurag']



# get the length of a Dictionary 

In [9]: len(my_dictionary)
Out[9]: 2


# Add new key and value to the dictionary 

In [10]: my_dictionary['site'] = 'eranurag.in'


In [11]: my_dictionary
Out[11]: {1: 'One', 'name': 'Anurag', 'site': 'eranurag.in'}


# Delete the Key and its value from a Dictionary 

In [12]: del my_dictionary['site']

In [13]: my_dictionary

Out[13]: {1: 'One', 'name': 'Anurag'}

 

Tuple as Key in a Dictionary:

As discussed earlier, dictionary keys should be a Immutable Object and hence we can use tuple ( which is also a Immutable object ) as a key in a Dictionary.

We can use tuple to define it as a Multi Dimensional Array.

In [14]: matrix = {}

In [15]: matrix[(1,2,3)] = 10

In [16]: matrix[(4,5,6)] = 20

In [17]: matrix
Out[17]: {(1, 2, 3): 10, (4, 5, 6): 20}

Now if we try to access the Keys which is not present in a dictionary, it throws a KeyError

In [18]: matrix[(10,11, 12)]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-18-53f026c33015> in <module>()
----> 1 matrix[(10,11, 12)]

KeyError: (10, 11, 12)

 

How to avoid such KeyError while accessing any Keys, because these error always terminate the execution of the process.

One way is to put such condition under Try-Except

Another way is to use get method of the dictionary –

In [19]: matrix.get((1,2,3), 0)
Out[19]: 10     # For this ket data is present in the matrix dictionary and hence returns its value

In [20]: matrix.get((10, 11, 12), 0)
Out[20]: 0     # This key does not exist in the matrix dictionary and hence returned the default value i.e., 0 instead of raising an exception, KeyError