Dictionaries in python are used to store key - value pairs and they may have non-numeric indexes.


The dict keyword is used to create dictionaries:

Inserting Data

Data can be inserted by specifying certain key and value.


In this example, 2 records have been inserted.

Accessing Values

Values can be accessed via their keys.

Let's look at the following example:


The key-value pair for Coke is set at line 3 and accessed at line 6.

Not Set Key

Accessing key that's not set in the array results in KeyError.

Let's look at the following example:

The dictionary doesn't contain any Coke key, so drinks["Coke"] causes an exception.

Iterating Elements

Let's have a program in which students scores are stored in dictionary and printed afterwards.


The following code is suitable for Python 3 but if you use Python 2, you need to replace items() with iteritems().

Removing Elements

That's done via the del keyword like in this example:

If unexisting key is attempted to be removed (like del drinks['Juice']) then a KeyError is thrown.

Checking if key exists

It can be done via the in keyword like in the following code:


Water key is not set thus Water is not printed.


Size is the count of the key-value pairs.

It can be accessed via the len function.

Let's look at this example:


4 records were inserted and 1 is deleted afterwards. This makes for 3 key-value pairs.