Python dictionary

Dictionaries are one of the built-in data types in Python. Like the language dictionary has words and their meaning written in it, the python dictionaries have 'key' and the 'value' corresponding to the 'key' stored in it. The python dictionary can be created by writing key-value pairs inside a curly bracket {}. An empty dictionary can be initiated as follows:

d = {}

Also, we can directly create a dictionary with initial key-value pairs. The key- value pairs must be in the format {key: value}. Following is an example.

d = {'A': 3, 'Animals': ['dog', 'lion']}

Here, we added two key-value pairs, {'A': 3} and { 'Animals': ['dog', 'lion']}.

Note that the values can be a number, a string, a list or even a dictionary. They keys of the dictionary, however, should be an immutable objects such as strings, numbers, and tuples.

Add new item to a dictionary

New items in a dictionary can be added to the dictionary as follows: 

d = {}
d['C'] = 43
d['V'] = 57
d['N'] = 38
d['K'] = 84
print(d)
{'C': 43, 'V': 57, 'N': 38, 'K': 84}

Access values in a dictionary

Values in a dictionary can be accesses by thier keys.
print(d['N'])
38

Number of items in a dictionary

The python standard function len() can be used with a dictionary to get the number of items in a dictionary.

print(len(d))
4

Get all keys or all values

All the keys and values of a dictionary can be got from calling the keys() and values() function associates with the dictionary as follows:
keys = d.keys()
values = d.values()
print(keys)
dict_keys(['C', 'V', 'N', 'K'])
print(values)
dict_values([43, 57, 38, 84])
In python 3, the above function return an iterator rather the actual list of the items we want. We have to call the list() function to get the list of the items we want. For example, if want a list of all the keys we write the python statement as follows.
keys = list(d.keys())
print(keys)
['C', 'V', 'N', 'K']
We now get a list of the keys. This output will have all the functions associated with 'python lists' available. The items() function gives us key-value pairs in form of tuple. For example,
items = list(d.items())
print(items)
[('C', 43), ('V', 57), ('N', 38), ('K', 84)]

Iterating over dictionary

We can iterate over dictionary in more than one way. First method is to directly iterate over the keys in dictionary.

for key in d:
    print(key, d[key])
C 43
V 57
N 38
K 84

In the above for loop we have iterated over the dictionary (represented by variable 'd') keys and have printed the keys and their values side-by-side. The values were accessed by their respective keys. To know how the 'for loop' works, see the post written here.

Similarly we can iterate over dictionary by using the items() function.

for k, v in d.items():
    print(k,v)
C 43
V 57
N 38
K 84

Delete dictionary item

The 'del' function is used to delete items in a dictionary.

del d['V']
print(d)
{'C': 43, 'N': 38, 'K': 84}

Update a dictionary

Lets say we have an initial dictionary. We want to update it from another dictionary. In this case the 'update()' function is used. This function adds any new keys present in the second dictionary into the first. If there is a key in first dictionary matching with second dictionary, then the value of the second dictionary will be overwritten in place of the value in first dictionary. Following is an example for clarity:

first_dict = {'A': 3,
              'B': 6,
              'C': 9,
              'D': 12}

second_dict = {'E': 16,
               'C': 20}

print(f'The first dictionary:\n{first_dict}')
print(f'The second dictionary:\n{second_dict}')

first_dict.update(second_dict)
print(f'The updated first dictionary:\n{first_dict}')
The first dictionary:
{'A': 3, 'B': 6, 'C': 9, 'D': 12}
The second dictionary:
{'E': 16, 'C': 20}
The updated first dictionary:
{'A': 3, 'B': 6, 'C': 20, 'D': 12, 'E': 16}

You can see that the 'update()' function added a new key, E, and also edited the existing value of the key, C, from the second dictionary.

Popular posts from this blog

Principal Coordinate analysis in R and python

Principal Coordinate Analysis (PCoA) in R