Dictionaries

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

Creation

The dict keyword is used to create dictionaries:

Inserting Data

Data can be inserted by specifying certain key and value.

Example:

In this example, 2 records have been inserted.

Accessing Values

Values can be accessed via their keys.

Let's look at the following example:

Output:

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.

Output:

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:

Output:

Water key is not set thus Water is not printed.

Size

Size is the count of the key-value pairs.

It can be accessed via the len function.

Let's look at this example:

Output:

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