Dictionaries

A dictionary (https://docs.python.org/3.4/tutorial/datastructures.html#dictionaries) is a data type that is an unordered collection of key and value pairs. Each key in a dictionary has an associated value. An example of a dictionary is:

    >>> my_dict = {1: "Hello", 2: "World"}
>>> my_dict

{1: 'Hello', 2: 'World'}

A dictionary is created by using the braces {}. At the time of creation, new members are added to the dictionary in the following format: key: value (shown in the preceding example). In the previous example 1 and 2 are keys while 'Hello' and 'World' are the associated values. Each value added to a dictionary needs to have an associated key.

The elements of a dictionary do not have an order i.e. the elements cannot be retrieved in the order they were added. It is possible to retrieving the values of a dictionary by iterating through the keys. Let's consider the following example:

    >>> my_dict = {1: "Hello", 2: "World", 3: "I", 4: "am",
5: "excited", 6: "to", 7: "learn", 8: "Python" }

There are several ways to print the keys or values of a dictionary:

    >>> for key in my_dict:

...

print(my_dict[value])

...

Hello

World

I

am

excited

to

learn

Python

In the preceding example, we iterate through the keys of the dictionary and retrieve the value using the key, my_dict[key]. It is also possible to retrieve the values using the values() method available with dictionaries:

    >>> for value in my_dict.values():

...

print(value)

...

Hello

World

I

am

excited

to

learn

Python

The keys of a dictionary can be an integer, string, or a tuple. The keys of a dictionary need to be unique and it is immutable, that is a key cannot be modified after creation. Duplicates of a key cannot be created. If a new value is added to an existing key, the latest value is stored in the dictionary. Let's consider the following example:

  • A new key/value pair could be added to a dictionary as follows:
       >>> my_dict[9] = 'test'

>>> my_dict

{1: 'Hello', 2: 'World', 3: 'I', 4: 'am', 5: 'excited',
6: 'to', 7: 'learn', 8: 'Python', 9: 'test'}
  • Let's try creating a duplicate of the key 9:
       >>> my_dict[9] = 'programming'

>>> my_dict

{1: 'Hello', 2: 'World', 3: 'I', 4: 'am', 5: 'excited',
6: 'to', 7: 'learn', 8: 'Python', 9: 'programming'}
  • As shown in the preceding example, when we try to create a duplicate, the value of the existing key is modified.
  • It is possible to have multiple values associated with a key. For example, as a list or a dictionary:
      >>> my_dict = {1: "Hello", 2: "World", 3: "I", 4: "am",
"values": [1, 2, 3,4, 5], "test": {"1": 1, "2": 2} }

Dictionaries are useful in scenarios like parsing CSV files and associating each row with a unique key. Dictionaries are also used to encode and decode JSON data