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:
Data can be inserted by specifying certain key and value.
Example:
In this example, 2 records have been inserted.
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
.
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.
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()
.
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.
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 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.