Python Dictionary

Facebooktwitterredditpinterestlinkedinmailby feather

Python Dictionary

A Python dictionary is a mutable collection of unordered key- values pair data. It stores key along with its value, so that a key can access its respective value.

A Python dictionary stores dictionary items that can be retrieved very fast by their key.

The keys must be unique within a dictionary. The dictionary’s value can be of any type, but the keys must be of an immutable data type such as numbers, strings, or tuples.

Creating a dictionary

A Python dictionary stores data in key-value pair within the curly bracket {}, where key and value are separated by a colon (:). For example:

Output:

Output:

Dictionary operations

Accessing value from the dictionary

We can access the value from a dictionary by using the index operator [], and the key is used inside the square brackets. Python also provides the get() method to access the value.  For example.

Output:                         

  • If we try to access a value that does not exist in the given dictionary then we get an error.

Output:

  • If we use the get() method for non-existing value. It will not show an error but return None. For example:

Output:

Modification (update) in Dictionary

We can update a dictionary by adding new key-value pair. The dictionary is mutable data type so its value can be updated or deleted by using specific keys.  For example:

Output:

Deletion in Dictionary

The element of the dictionary can be deleted by using the del keyword. We can either remove the single element or clear entire dictionary.

Output:

Python provides the clear() method to clear all element of dictionary. It returns an empty dictionary.

Output:

Properties of Dictionary Keys

There are few points to remember about dictionary keys.

  1. In the dictionary, the duplicate key is not allowed, which means we cannot define the same key for multiple values. If we declare the same key for multiple values, then, it will store the last assigned value.  Consider the following example.

Output:

  • The dictionary keys must be immutable, which means we can use numbers, strings or tuple as a key. But mutable like [‘key’] is  not allowed. For example:

Output:

Built-in Dictionary functions

The built-in functions and their descriptions are given below:

Sr. no. Functions Description
1. len(dict) It is used to compute the length of dictionary
2. cmp(dict1, dict2) It compares the elements of both the dictionary.
3. str(dict) It converts the dictionary into printable string representation.
4. type(variable) It is used to print the type of the passed variable.

Facebooktwitterredditpinterestlinkedinmailby feather