Dictionary

A dictionary is an object that stores a collection of data. Each element in a dictionary has two parts: a key and a value. A key is used to locate a specific value.

Creating a Dictionary

Create a dictionary by enclosing the elements inside a set of curly braces ( {} ). An element consists of a key, followed by a colon, followed by a value. The elements are separated by commas.

Example:

phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555-3333'}

The values in a dictionary can be objects of any type, but the keys must be immutable objects.

Retrieving a Value from a Dictionary

To retrieve a value from a dictionary, you simply write an expression in the following general format:

dictionary_name[key]

If the key exists in the dictionary, the expression returns the value that is associated with the key. If the key does not exist, a KeyError exception is raised.

A KeyError exception is raised if you try to retrieve a value from a dictionary using a nonexistent key. To prevent such an exception, you can use the in operator to determine whether a key exists before you try to use it to retrieve a value.

Adding Elements to an Existing Dictionary

Dictionaries are mutable objects. You can add new key-value pairs to a dictionary with an assignment statement in the following general format:

dictionary_name[key] = value

If key already exists in the dictionary, its associated value will be changed to value. If the key does not exist, it will be added to the dictionary, along with value as its associated value.

Example:

>>> phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555−3333'}

>>> phonebook['Sam'] = '555−0123'

>>> phonebook['Ashraf'] = '555−4444'

>>> phonebook

{'Ashraf': '555-4444', 'Anwar': '555−3333', 'Sam': '555−0123','Amjad': '555−2222'}

Note: The elements in a dictionary are not stored in any particular order.

Deleting Elements

An existing key-value pair can be deleted from a dictionary with the del statement. Here is the general format:

del dictionary_name[key]

After the statement executes, the key and its associated value will be deleted from the dictionary. If the key does not exist, a KeyError exception is raised.

Example:

>>> phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555−3333'}

>>> del phonebook['Ashraf']

>>> phonebook

{'Amjad':'555−2222', 'Anwar':'555−3333'}

Getting the Number of Elements in a Dictionary

The built-in len function is used to get the number of elements in a dictionary.

Example:

>>> phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555−3333'}

>>> num_items = len(phonebook)

>>> print(num_items)

Creating an Empty Dictionary

Sometimes you need to create an empty dictionary and then add elements to it as the program executes. An empty set of curly braces can be used to create an empty dictionary.

>>> phonebook = {}

>>> phonebook['Ashraf'] = '555-1111'

>>> phonebook['Amjad'] = '555-2222'

The built-in dict() method can also be used to create an empty dictionary, as shown in the following statement:

phonebook = dict()

After this statement executes, the phonebook variable will reference an empty dictionary.

Using the for Loop to Iterate over a Dictionary

The for loop is used in the following general format to iterate over all the keys in a dictionary:

for var in dictionary:

statement

statement

etc.

This loop iterates once for each element in the dictionary. Each time the loop iterates, var is assigned a key.

Example:

>>> phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555−3333'}

>>> for key in phonebook:

print(key)

>>> phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555−3333'}

>>> for key in phonebook:

print(key, phonebook[key])