0% found this document useful (0 votes)
22 views

10.6 Dictionaries - Jupyter Notebook

Dictionaries in Python are unordered collections of items consisting of keys and their corresponding values. A dictionary is created by placing items inside curly braces separated by commas where each item contains a key-value pair. Keys can be any immutable type like strings, numbers, or tuples while values can be any data type. Dictionaries provide fast access and modification of elements using keys.

Uploaded by

bharathms525
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

10.6 Dictionaries - Jupyter Notebook

Dictionaries in Python are unordered collections of items consisting of keys and their corresponding values. A dictionary is created by placing items inside curly braces separated by commas where each item contains a key-value pair. Keys can be any immutable type like strings, numbers, or tuples while values can be any data type. Dictionaries provide fast access and modification of elements using keys.

Uploaded by

bharathms525
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Sets and Dictionaries

Table of Contents

Dictionaries

Dictionaries in Python

A dictionary is an unordered collection of items, consists of keys and values.

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.

1. Creating Python Dictionary


Creating a dictionary is as simple as placing items inside curly braces { } separated by commas.

An item has a key and a corresponding value that is expressed as a pair (key: value).

An example of a Dictionary Dict:

In [ ]:

1 D={"key1":1,"key2":"2","key3":[3, 5]}
2 D

executed in 55ms, finished 12:06:29 2021-11-27

NOTE:

1. Each key is separated from its value by a colon ":".


2. Commas separate the items, and
3. The whole dictionary is enclosed in curly braces. An empty dictionary without any items is written with just
two curly braces, like this "{}".

In [ ]:

1 type(D)

executed in 19ms, finished 12:07:33 2021-11-27

In [ ]:

1 Dict={"key1":1,"key2":"2","key3":[3,3,3],"key4":(4,4,4),('key5'):5,(0,1):6}
2 Dict

executed in 25ms, finished 12:08:01 2021-11-27

we can also create a dictionary using the built-in dict() function.


In [ ]:

▾ 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)

executed in 19ms, finished 22:29:06 2021-11-28

Accessing Elements from Dictionary

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.

The keys can be strings:

In [ ]:

▾ 1 # get vs [] for retrieving elements


2 my_dict = {'name': 'Jack', 'age': 26}
3
4 # Output will be for name key: Jack
5 print(my_dict['name'])
6
7 # Output will be for age key: 26
8 print(my_dict.get('age'))

In [ ]:

▾ 1 # Trying to access keys which doesn't exist throws error


2 # Output None
3 print(my_dict.get('address'))
4
5 # KeyError
6 print(my_dict['address'])
In [ ]:

1 Dict={"key1":1,"key2":"2","key3":[3,3,3],"key4":(4,4,4),('key5'):5,(0,1):6}
2 Dict

executed in 38ms, finished 22:33:20 2021-11-28

In [ ]:

1 Dict["key1"]

executed in 26ms, finished 22:33:21 2021-11-28

Keys can also be any immutable object such as a tuple:

In [ ]:

1 Dict[(0,1)]

executed in 6ms, finished 22:33:23 2021-11-28

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.

Changing and Adding Dictionary elements

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 [ ]:

▾ 1 # Changing and adding Dictionary Elements


2 my_dict = {'name': 'Jack', 'age': 26}
3
4 # update value
5 my_dict['age'] = 27
6
7 #Output: {'age': 27, 'name': 'Jack'}
8 print(my_dict)
9
10
11
12 # add item
13 my_dict['address'] = 'Downtown'
14
15 # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
16 print(my_dict)

executed in 18ms, finished 22:35:11 2021-11-28


Removing elements from Dictionary

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 [ ]:

▾ 1 # Removing elements from a dictionary


2
3 # create a dictionary
4 squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
5
6 # remove a particular item, returns its value
7 # Output will be: 16
8 print(squares.pop(4))
9
10 # Output: {1: 1, 2: 4, 3: 9, 5: 25}
11 print(squares)

In [ ]:

▾ 1 # remove an arbitrary item, return (key,value)


2 # Output: (5, 25)
3 print(squares.popitem())
4
5 # Output: {1: 1, 2: 4, 3: 9}
6 print(squares)
7

In [ ]:

▾ 1 # remove all items


2 squares.clear()
3
4 # Output: {}
5 print(squares)

In [ ]:

▾ 1 # delete the dictionary itself


2 del squares
3
4 # Throws Error
5 print(squares)

Another Example of Creating a dictionary


In [ ]:

▾ 1 release_year_dict = {"Thriller":"1982", "Back in Black":"1980", \


2 "The Dark Side of the Moon":"1973", "The Bodyguard":"1992", \
3 "Bat Out of Hell":"1977", "Their Greatest Hits (1971-1975)":"1976
4 "Saturday Night Fever":"1977", "Rumours":"1977"}
5 release_year_dict

executed in 18ms, finished 12:09:34 2021-11-27

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.

Figure 9: Table representing a Dictionary


You will need this dictionary for the next two questions :

In [ ]:

1 soundtrack = { "The Bodyguard":"1992", "Saturday Night Fever":"1977"}


2 soundtrack

executed in 18ms, finished 12:09:56 2021-11-27


In [ ]:

1 type(soundtrack)

executed in 19ms, finished 12:11:20 2021-11-27

In the dictionary "soundtrack_dict" what are the keys ?

In [ ]:

1 soundtrack.keys()

executed in 20ms, finished 12:10:08 2021-11-27

In [ ]:

1 type(soundtrack.keys())

executed in 17ms, finished 12:11:03 2021-11-27

Click here for the solution

In the dictionary "soundtrack_dict" what are the values ?

In [ ]:

1 soundtrack.values()

executed in 18ms, finished 12:10:28 2021-11-27

In [ ]:

1 type(soundtrack.values())

executed in 22ms, finished 12:10:48 2021-11-27

Click here for the solution

You can retrieve the values based on the names:

In [ ]:

1 release_year_dict

executed in 19ms, finished 12:11:39 2021-11-27

In [ ]:

1 release_year_dict['Thriller']

executed in 11ms, finished 12:11:48 2021-11-27

This corresponds to:


Table used to represent accessing the value for "Thriller"

Similarly for The Bodyguard

In [ ]:

1 release_year_dict['The Bodyguard']

executed in 19ms, finished 12:11:58 2021-11-27

Accessing the value for the "The Bodyguard"

Now let us retrieve the keys of the dictionary using the method release_year_dict():
In [ ]:

1 release_year_dict.keys()

executed in 5ms, finished 12:12:05 2021-11-27

You can retrieve the values using the method values() :

In [ ]:

1 release_year_dict.values()

executed in 12ms, finished 12:12:09 2021-11-27

We can add an entry:

In [ ]:

1 release_year_dict['Graduation']='2007'
2 release_year_dict

executed in 25ms, finished 12:12:35 2021-11-27

We can delete an entry:

In [ ]:

1 del(release_year_dict['Thriller'])
2 del(release_year_dict['Graduation'])
3 release_year_dict

executed in 15ms, finished 12:12:56 2021-11-27

We can verify if an element is in the dictionary:

In [ ]:

1 'The Bodyguard' in release_year_dict

executed in 25ms, finished 12:13:17 2021-11-27

In [ ]:

1 'The Santosh' in release_year_dict

executed in 18ms, finished 12:13:27 2021-11-27

Dictionary Built-in Functions

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 [ ]:

▾ 1 # Dictionary Built-in Functions


2 squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
3
4 # Output will be: False
5 print(all(squares))
6
7 # Output will be: True
8 print(any(squares))
9
10 # Output will be: 6
11 print(len(squares))
12
13 # Output will be: [0, 1, 3, 5, 7, 9]
14 print(sorted(squares))

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 [ ]:

Click here for the solution

b) Use the dictionary to find the total sales of "Thriller":

In [ ]:

Click here for the solution

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 sales​from the dictionary using the method "values":

In [ ]:

Click here for the solution

You might also like