10.6 Dictionaries - Jupyter Notebook
10.6 Dictionaries - Jupyter Notebook
Table of Contents
Dictionaries
Dictionaries in Python
It is helpful to compare a dictionary to a list. Instead of the numerical indexes such as a list, dictionaries have
keys. These keys are labels that are used to access values within a dictionary.
A Comparison of a Dictionary to a list: Instead of the numerical indexes like a list, dictionaries have
keys.
An item has a key and a corresponding value that is expressed as a pair (key: value).
In [ ]:
1 D={"key1":1,"key2":"2","key3":[3, 5]}
2 D
NOTE:
In [ ]:
1 type(D)
In [ ]:
1 Dict={"key1":1,"key2":"2","key3":[3,3,3],"key4":(4,4,4),('key5'):5,(0,1):6}
2 Dict
▾ 1 # empty dictionary
2 my_dict = {}
3
4 # dictionary with integer keys
5 my_dict = {1: 'apple', 2: 'ball'}
6 print("Dictionary with integer keys my_dict:", my_dict)
7
8 # dictionary with mixed keys
9 my_dict1 = {'name': 'John', 1: [2, 4, 3]}
10 print("Dictionary with mixed keys my_dict:", my_dict1)
11
12 # using dict()
13 my_dict2 = dict({1:'apple', 2:'ball'})
14 print("Dictionary with dict function:", my_dict2)
15
16 # from sequence having each item as a pair
17 my_dict3 = dict([(1,'apple'), (2,'ball')])
18 print("Dictionary with sequence having each item as a pair:", my_dict3)
While indexing is used with other data types to access values, a dictionary uses keys.
Keys can be used either inside square brackets [ ] or with the get( ) method.
NOTE:
If we use the square brackets [ ], KeyError is raised in case a key is not found in the dictionary.
On the other hand, the get() method returns None if the key is not found.
In [ ]:
In [ ]:
1 Dict={"key1":1,"key2":"2","key3":[3,3,3],"key4":(4,4,4),('key5'):5,(0,1):6}
2 Dict
In [ ]:
1 Dict["key1"]
In [ ]:
1 Dict[(0,1)]
In summary, like a list, a dictionary holds a sequence of elements. Each element is represented by a key and its
corresponding value. Dictionaries are created with two curly braces containing keys and values separated by a
colon.
For every key, there can only be a single value, however, multiple keys can hold the same value. Keys must be
of immutable type (string, number or tuple with immutable elements) but values can be any data type.
Dictionaries are mutable. We can add new items or change the value of existing items using an assignment
operator.
If the key is already present, then the existing value gets updated. In case the key is not present, a new (key:
value) pair is added to the dictionary
In [ ]:
We can remove a particular item in a dictionary by using the pop() method. This method removes an item with
the provided key and returns the value.
The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary.
All the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
In [ ]:
In [ ]:
In [ ]:
In [ ]:
It is helpful to visualize the dictionary as a table, as in figure 9. The first column represents the keys, the second
column represents the values.
You will need this dictionary for the next two questions :
In [ ]:
1 type(soundtrack)
In [ ]:
1 soundtrack.keys()
In [ ]:
1 type(soundtrack.keys())
In [ ]:
1 soundtrack.values()
In [ ]:
1 type(soundtrack.values())
In [ ]:
1 release_year_dict
In [ ]:
1 release_year_dict['Thriller']
In [ ]:
1 release_year_dict['The Bodyguard']
Now let us retrieve the keys of the dictionary using the method release_year_dict():
In [ ]:
1 release_year_dict.keys()
In [ ]:
1 release_year_dict.values()
In [ ]:
1 release_year_dict['Graduation']='2007'
2 release_year_dict
In [ ]:
1 del(release_year_dict['Thriller'])
2 del(release_year_dict['Graduation'])
3 release_year_dict
In [ ]:
In [ ]:
Built-in functions like all( ), any( ), len( ), cmp( ), sorted( ), etc. are commonly used with dictionaries to perform
different tasks.
all( ) - Return True if all keys of the dictionary are True (or if the dictionary is empty).
any( ) - Return True if any key of the dictionary is true. If the dictionary is empty, return False.
len( ) - Return the length (the number of items) in the dictionary.
cmp( ) - Compares items of two dictionaries. (Not available in Python 3)
sorted( ) - Return a new sorted list of keys in the dictionary.
In [ ]:
Quiz
The Albums 'Back in Black', 'The Bodyguard' and 'Thriller' have the following music recording sales
in millions 50, 50 and 65 respectively:
a) Create a dictionary “album_sales_dict” where the keys are the album name and the sales in
millions are the values.
In [ ]:
In [ ]:
c) Find the names of the albums from the dictionary using the method "keys":
In [ ]:
1
Click here for the solution
d) Find the names of the recording salesfrom the dictionary using the method "values":
In [ ]: