Dictionaries

Probably the 2nd most important data structure after lists and another Python favourite.

This is the way you define an empty dictionary and assign it to the variable my_dict.

my_dict = {}
my_dict = dict()

A dictionary holds a key and a value that correspond to each other. As with lists you can fill a dictionary with any Python object you choose like  numbers, strings, booleans, other dictionaries, other data structures and so on. Below are some examples of dicitonaries.

a_dict = { 'A' : 32, 'B': 11, 'C':345 }
b_dict = {'2021-01-01': 17.234, '2021-01-02':18.332}

In order to access elements in a dictionary you have to use its keys.

fist_value_a = a_dict['A']
fist_value_b = b_dict['2021-01-01']

If you want to access values or keys from a dictionary you can apply the .values() or .keys() methods respectively.

a_dict.values()  
a_dict.keys() 

To add a value in a dictionary, you chose a corresponding key and register it.

a_dict['D'] = 1
b_dict['2021-01-03'] = 22

Note that the value is added at the end of the dictionary. If you would like to add the value at the beginning of the dictionary, one way is to use the .update() method.

price = {'2020-12-31':16.9876}
b_dict.update(price)

If you want to delete a value from a dictionary a quick way to do it is using the del function. Same goes for deleting the entire dictionary. For example

del b_dict['2021-01-01']
del a_dict['A']
del a_dict
del b_dict

If you want to check whether a key is in a dict, or not, you can use the in or not in python functions.

'2021-01-01' in b_dict
'2021-01-01' not in b_dict

Finally you can construct dictionaries out of 2 lists.

list1 = ['2021-01-01', '2021-01-02', '2021-01-03']

list2 = [ 17.234, 18.332, 16.978 ]

combined_dict = dict(zip(list1, list2))