Dictionary

Holding data as key-value pairs is important especially in distributed algorithms. In Python, a collection of these key-value pairs is stored as a data structure called a dictionary. To create a dictionary, a key should be chosen as an attribute that is best suited to identify data throughout data processing. The value can be an element of any type, for example, a number or string. Python also always uses complex data types such as lists as values. Nested dictionaries can be created by using a dictionary as the data type of a value.

To create a simple dictionary that assigns colors to various variables, the key-value pairs need to be enclosed in { }. For example, the following code creates a simple dictionary consisting of three key-value pairs:

>>> bin_colors ={
"manual_color": "Yellow",
"approved_color": "Green",
"refused_color": "Red"
}
>>> print(bin_colors)
{'manual_color': 'Yellow', 'approved_color': 'Green', 'refused_color': 'Red'}

The three key-value pairs created by the preceding piece of code are also illustrated in the following screenshot:

Now, let's see how to retrieve and update a value associated with a key:

  1. To retrieve a value associated with a key, either the get function can be used or the key can be used as the index:
>>> bin_colors.get('approved_color')
'Green'
>>> bin_colors['approved_color']
'Green'
  1. To update a value associated with a key, use the following code:
>>> bin_colors['approved_color']="Purple"
>>> print(bin_colors)
{'manual_color': 'Yellow', 'approved_color': 'Purple', 'refused_color': 'Red'}

Note that the preceding code shows how we can update a value related to a particular key in a dictionary.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset