Using Python dictionary

A dictionary is represented as a key-value container known as a mapping in Python. In other words, a Python dictionary is a set of key-value pairs with the necessity that the keys are distinctive (in a dictionary). 

Key: The key is the desired key to be indexed.

Value: The value to be returned.

Dictionaries are usually referenced by key; they have very fast lookups. Unlike a sequence-like datatype like a list,which is indexed by a range of numbers, a dictionary is indexed by the keys, which must be unique and immutable. The keys can be immutable data types, like tuples, strings, and numbers. The value can accommodate any data type, whether immutable or mutable.

Syntax of Python dictionary

The Python dictionary can be created in many ways. The literal initiation of a dictionary is usually enclosed in a pair of braces with the key-value pairs.

d = { }   #Empty dictionary

d = {"key" : "value"}  #Dictionary with initial values

Another way to create a dictionary is by using the method dict()

a = dict() # empty dictionary
a = dict([("key", "value")]) #Creating the key-value pairs as list
b = dict({"key":"value"}) #creating a dictionary with the dict() method
c = dict(key="value") # Explicit keyword arguement

Modifying a dictionary

To add items to the dictionary, we can easily create a new key with a value using the square bracket. Therefore,

d = {"name":"John", "age":31}
d["country"] = "Russia"
#{'name': 'John', 'age': 31, 'country': 'Russia'}

The new data has been added to the dictionary. 

We can also change the items in a dictionary by using the key. Let's say we want to change the country, it can be done as follows:

d["country"] = "China"

The new dictionary will be {'name': 'John', 'age': 31, 'country': 'China'}

We can also decide to delete items from the dictionary. We just need to specify the key, using the del function.

del d["age"] 

The new dictionary will be {'name': 'John', 'country': 'China'}.

Finally, we can decide to clear the whole key-value pair in the dictionary. The clear() method can be used to empty the dictionary.


The new dictionary is an empty one {}.

Accessing a dictionary.

The key and value of a dictionary can be accessed using either a for loop, list comprehension, or a plain list.

Given a dictionary like:

a = {"Texas":"Austin", "Georgia":"Atlanta", "Maine":"Augusta", "Colorado":"Denver"}

Using a for loop, we traverse the keys of the dictionary to get the key-value pairs in the dictionary. For example

for key in a:
 print(key, a[key])
#Texas Austin
#Georgia Atlanta
#Maine Augusta
#Colorado Denver

We can also use the items() method to loop both the key and value simultaneously.

for key, value in a.items():
    print(key, value)
#Texas Austin
#Georgia Atlanta
#Maine Augusta
#Colorado Denver

List comprehension can be used to access the keys of the dictionary. For example

print([keys for keys in a])
#['Texas', 'Georgia', 'Maine', 'Colorado']

The list of keys can be gotten by using the keys() method.

#dict_keys(['Texas', 'Georgia', 'Maine', 'Colorado'])

The list of values can be gotten by using the values() method.

#dict_values(['Austin', 'Atlanta', 'Augusta', 'Denver'])

The items() method can be used to get the both the keys and the corresponding values.

dict_items([('Texas', 'Austin'), ('Georgia', 'Atlanta'), ('Maine', 'Augusta'), ('Colorado', 'Denver')])

When accessing a dictionary, one might encounter a key error exception if a nonexistent key is used for a lookup. In this case, one can use the get() method to avoid the key error. The get() method allows one to specify a default value if the key is non-existent. So, a value is returned instead of the exception error.

Note that the dictionary does not retain the non existent key-value pair introduced by the get() method. 

print(a.get("Michigan", "Lansing"))

So, if you want to retain the key-value pair, you can use the setdefault() method. For example.

print(a.setdefault("Michigan", "Lansing"))
#{'Texas': 'Austin', 'Georgia': 'Atlanta', 'Maine': 'Augusta', 'Colorado': 'Denver', 'Michigan': 'Lansing'}

Dictionary comprehension

Dict comprehension is more like converting one dictionary to another. It's like a concise way of creating a dictionary.

The syntax for dict comprension is represented as follows:

a = {k:v for k,v in [('key', 'value',)]}

Merging dictionary

The symbol ** is used to denote a dictionary of keyword arguments. The symbol is used to combine or merge a dictionary when enclosed with a dict bracket. 

Let's consider the dictionaries as follows:

a = {"Texas":"Austin", "Georgia":"Atlanta", "Maine":"Augusta", "Colorado":"Aspen"}
b = {"Arizona": "Phoenix", "Carlifornia":"Sacremento", "Colorado":"Denver"}
c = {**a, **b}
#{'Texas': 'Austin', 'Georgia': 'Atlanta', 'Maine': 'Augusta', 'Colorado': 'Denver', 'Arizona': 'Phoenix', 'Carlifornia': 'Sacremento'}

Notice from the output that the duplicate key maps to the lattermost value (for example, "Denver" overrides "Aspen").

The ChainMap() method can also be used to merge dictionaries. In this case, the foremost value takes precedence for a given key rather than the last("Aspen" overrides "Denver").

from collections import ChainMap
a = {"Texas":"Austin", "Georgia":"Atlanta", "Maine":"Augusta", "Colorado":"Aspen"}
b = {"Arizona": "Phoenix", "Carlifornia":"Sacremento", "Colorado":"Denver"}
print(dict(ChainMap(a, b)))
#{'Arizona': 'Phoenix', 'Carlifornia': 'Sacremento', 'Colorado': 'Aspen', 'Texas': 'Austin', 'Georgia': 'Atlanta', 'Maine': 'Augusta'}


Literally, creating a dictionary involves a key-value pair enclosed in a curly bracket. The key must be unique and hashable.

The Dict() constructor can also be used to create dictionaries.

Dictionaries can be modified using the square brackets along with the keys.

The keys and values in a dictionary can be accessed using various techniques, such as for loops and list comprehension.

When accessing a value, In order to avoid KeyError exceptions, the get() and setdefault() methods can be used.

Finally, dictionaries can be merged using the symbol ** enclosed in curly brackets and the ChainMap() method.