Dictionaries¶
Like a list, a dictionary, or dict
, is a collection of values. Dictionaries consist of several key-value pairs. Each pair has a key which is used to access the value associated with it. The key in a dictionary is much like an index in a list, but whereas an index must be an integer, a key can be of many different data types.
Dictionaries are created using the following syntax:
my_dict = {key1:value1, key2:value2, ..., keyN:valueN}
Basic Dictionary Operations¶
The cell below defines a simple dictionary that is used to store salary information for employees.
salary_dict = {'Anna':43700, 'Beth': 50250}
print(salary_dict)
{'Anna': 43700, 'Beth': 50250}
We can access individual values of the dictionary using the associated keys.
print(salary_dict['Anna'])
print(salary_dict['Beth'])
43700
50250
We can add new key-value pairs to a dictionary as follows:
salary_dict['Craig'] = 47600
salary_dict['Drew'] = 37400
print(salary_dict)
{'Anna': 43700, 'Beth': 50250, 'Craig': 47600, 'Drew': 37400}
We can also update values in a dictionary.
salary_dict['Drew'] = 39800
print(salary_dict)
{'Anna': 43700, 'Beth': 50250, 'Craig': 47600, 'Drew': 39800}
We can delete entries from a dictionary using the del keyword.
del salary_dict['Craig']
print(salary_dict)
{'Anna': 43700, 'Beth': 50250, 'Drew': 39800}
We can use the len()
function on dictionaries to determine the number of values that they contain.
print(len(salary_dict))
3