Python Dictionaries

A dictionary represents a group of elements arranged in the form of key-value pairs. In the dictionary, the first element is considered as 'key' and the immediate next element is taken as its 'value'. The key and its value are separated by a colon (:). All the key-value pairs in a dictionary are inserted in curly braces {}. Let's take a dictionary by the name 'dict' that contains employee details:

dict = {'Name': 'Chandra', 'Id': 200, 'Salary': 9080.50}

Here, the name of the dictionary is 'dict'. The first element in the dictionary is a string 'Name'. So, this is called 'key'. The second element is 'Chandra' which is taken as its 'value'. Observe that the key and its value are separated by a colon. Similarly, the next element is 'Id' which becomes 'key' and the next element '200' becomes its value. Finally, 'Salary' becomes key and '9080.50' becomes its value. So, we have 3 pairs of keys and values in this dictionary.

dictionary example

A Python program to create a dictionary with employee details and retrieve the values upon giving the keys.


Operations on Dictionaries

To access the elements of a dictionary, we should not use indexing or slicing. For example, dict[0] or dict[1:3] etc. expressions will give error. To access the value associated with a key, we can mention the key name inside the square braces, as: dict['Name']. This will return the value associated with 'Name'.

If we want to know how many key-value pairs are there in a dictionary, we can use the len() function.

We can modify the existing value of a key by assigning a new value, as shown in the following statement:

dict['Salary'] = 10500.00

We can also insert a new key-value pair into an existing dictionary. This is done by mentioning the key and assigning a value to it, as shown in the following statement:

dict['Dept'] = 'Finance'

This pair may be added at any place in the dictionary.

Suppose, we want to delete a key-value pair from the dictionary, we can use del statement as:

del dict['Id']

To test whether a 'key' is available in a dictionary or not, we can use 'in' and 'not in' operators. These operators return either True or False. Consider the following statement:

'Dept' in dict

'Gender' not in dict

We can use any datatypes for values. For example, a value can be a number, string, list, tuple or another dictionary. But keys should obey the following rules:

Keys should be unique. It means, duplicate keys are not allowed. If we enter same key again, the old key will be overwritten and only the new key will be available. Consider the following example:

emp = {'Nag':10, 'Vishnu':20, 'Nag':30}

print(emp)

Keys should be immutable type. For example, we can use a number, string or tuples as keys since they are immutable. We cannot use lists or dictionaries as keys. If they are used as keys, we will get 'TypeError'.

emp = {['Nag']:10, 'Vishnu':20, 'Raj':30}

TypeError: unhashable type: 'list'