0% found this document useful (0 votes)
15 views41 pages

Lesson 9 Dictionaries

Lesson 9 covers Python dictionaries, a data structure that associates unique keys with values, allowing for efficient data retrieval. It includes creating, modifying, and removing dictionary items, as well as using built-in functions to manage and access dictionary data. The lesson also features exercises to reinforce understanding of dictionary operations and sorting techniques.

Uploaded by

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

Lesson 9 Dictionaries

Lesson 9 covers Python dictionaries, a data structure that associates unique keys with values, allowing for efficient data retrieval. It includes creating, modifying, and removing dictionary items, as well as using built-in functions to manage and access dictionary data. The lesson also features exercises to reinforce understanding of dictionary operations and sorting techniques.

Uploaded by

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

Lesson 9: Python Data Structures 2:

Dictionaries
Introduction to Python Programming
Lesson 9: Python Data Structures 2:
Dictionaries

Lesson Overview


Creating and Using a Dictionary

More Dictionary Features

Dictionary Examples

Exercises.
Introduction

A dictionary in Python is

another type of structure you


can use to store data.

Dictionaries, as opposed to
lists and tuples, are set up so
that the values aren't
associated with an index.
Instead, they're associated
with a key, which is just some
unique value.

So, any time you want access
to a value, you just have to
provide the key.

3
Creating and Using a Dictionary:
Dictionary Basics


One common issue with lists is sometimes
finding an item proves to be difficult.

You’ve to perform a sequential search to find an
item whose index you don’t know.

It might be possible to improve upon the
performance of the searches by employing
different algorithms but you still need to search
through the list.
Dictionaries however make finding items easily

by using a special and unique value called a key.

4
Dictionary Basics


A different key is associated with each record in
a dictionary.
Each entry is referred to as a key-value pair.


Now any time you want to get access to a record,
you just provide the key.
Some other languages call these structures

hashes or associative arrays.

5
Creating a Dictionary

The syntax for creating a


dictionary is simple. Here’s an


empty dictionary called
my_dictionary.
my_dictionary={}

Each item in a dictionary need to
contain a key and a value.
days_in_month={‘Jan’:31}

The key comes first followed by a
colon and the value.

You can use different data types
for key in a single dictionary.
6
Creating a Dictionary

Starting a Dictionary with


Multiple Values
days_in_month = {'Jan':31, 'Feb':28, 'Mar':31}

Placing One Pair Per Line
days_in_month = {'Jan':31,
'Feb':28,
'Mar':31}

In cases where these values take more
characters, splitting the code up like this
really increases readability.

7
Printing from a Dictionary


To print the whole
dictionary – just pass
the dictionary name to
the print function like
lists and tuples.
print(days_in_month)

If you want to print a
specific item- pass the
key of that item.
print(days_in_month[‘Jan’])

8
More Dictionary Features: Listing the
Keys and the Values


Python provides some
helpful functions to make
it easier to work with
dictionaries.

For example the keys()
and values() function
allows to print the keys
and values in a dictionary.
print(days_in_month.keys())
print(days_in_month.values())

The return is a list
structure.
9
Listing the Keys and the Values


Two things to notice with
these functions.

Each one returns a list structure-
useful when you want to store the
list in a variable for future use.

The second is the order. Before it
used to be unordered- meaning the
order can vary. But now it’s ordered
as dictionary has been made to be
ordered.

10
More Dictionary Features


Listing the Key-Value Pairs
print (days_in_month.items())

This function is similar to keys( ) and values( ),
except that it returns a list of key-value tuples.

11
More Dictionary Features


Testing whether a key is present

If you attempt to access an item with a key that isn't present in the
dictionary, you'll get a KeyError. You can avoid this by testing to see if a
key is in the dictionary before you attempt to access it.

To test if a key is present in the dictionary list
the key, the keyword in and the dictionary name.
print ('Feb' in days_in_month)

This returns True or False depending on whether
the key is in the dictionary.

12
More Dictionary Features

13
Adding Values


To add items to the dictionary – type the name of
the dictionary with the key inside square
brackets and an equal sign followed by the value
you want to be stored
days_in_month ['Apr'] = 20
You can change the value by repeating the line

with a different value.


days_in_month ['Apr'] = 30

14
Adding Values

15
Combining Dictionaries


It is common to put
together two different
dictionaries.
For this, you can use the

update( ) function.

16
Removing Items from a Dictionary

Sometime after populating your dictionary – you


might want to remove items from it.



You can use del to do this. Here is the syntax:-
del days_in_month ['Apr']

If you pass a key that’s not in the dictionary –
you will get KeyError message.

This means that you should first check to see if
the key is present using the keyword in before
you try to delete anything

17
Removing Items from a Dictionary


It's also likely that at
some point, you might
want to remove all of the
items in your dictionary.

For that, there's the
clear( ) function.

This function will leave
you with an empty
dictionary variable, as
opposed to using del,
which removes a single
value.
18
Accessing Values using the get()
Function


We saw how to access individual items by placing
the dictionary name and a set of square brackets
with the key inside.
The problem is that if the key doesn't exist in the

dictionary, the program crashes and you get a


KeyError message.

To avoid this we can use the get() function which
returns None if the key doesn’t exist.
print (days_in_month.get('January'))

19
Accessing Values using the get()
Function


The other interesting thing about get( ) is that
you can provide a default value, instead of None,
to be returned if the key isn't present.

20
Dictionary Examples: Letting Users Add
Words to a Dictionary

Let's try a program that will make use of the


dictionary's ability to quickly look up values.



It'll also prompt the user for words and keep track of
the number of times a word is entered.

To do this with a dictionary, you’ll need to make the
key be the user's word and have the value be the
number of times it was entered.

You'll need to have some sentinel value for the user
to enter when they're done entering words- we will
use -999 for this.

When the user is done entering words, print the
word and the number of times it was entered:
21
Dictionary Examples: Letting Users Add
Words to a Dictionary

22
Dictionary Examples: Letting Users Add
Words to a Dictionary


You can print the items in sorted form by using
the sort function from lists.

23
Dictionary Examples: Letting Users Add
Words to a Dictionary

24
Displaying Words by Number of Times
Entered

What if you wanted to print out the words sorted


by the number of times they’re entered?



This is a bit more problematic because while
you're able to pull out the values and sort them
just fine, there's no way to get access to the
word, the key, using only the value.

There are a number of ways to do this.

One way, as you’ll learn here, is by doing a
manual sort on your values and keeping track of a
list of keys in the correct order.

25
Displaying Words by Number of Times
Entered


First, create an empty list to hold your keys. Then
write a loop that goes through each key in the
dictionary. Next, figure out where in the list this key
should be added. To do this, use a while loop that
starts at index 0 and stops when the counter reaches
the length of the list.

Inside the loop, the code simply gets the word out of
the sorted list and then compares the number
associated with that word to the number associated
with the current word. If the list's word number is
greater, then it’s found where the current word
should go, so it stops looping and inserts this word
into the list at that position.
26

Displaying Words by Number of Times
Entered

27
Exercises

Python: Sort (ascending and descending) a


dictionary by value

28
Exercises


Possible solution:-

29
Exercises

Write a Python script to concatenate following


dictionaries to create a new one.



Sample Dictionary :
dic1={1:10, 2:20}

dic2={3:30, 4:40}

dic3={5:50,6:60}

Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}


30
Exercises


Possible solution:

31
Exercises


Write a Python script to print a dictionary where
the keys are numbers between 1 and 15 (both
included) and the values are square of keys.

32
Exercises


Possible solution:

33
Exercises

Write a Python program to sum all the items in a


dictionary.

34
Exercises


Possible solution:

35
Exercises

Write a Python program to map two lists into a


dictionary.

36
Exercises


Possible solution:

37
Exercises


Write a Python program to remove duplicates
from Dictionary.

38
Exercises


Example:

39
Lesson 9 Review


In this lesson, you added to your knowledge of
Python's data structures by working with dictionaries.
You saw that these structures enable you to associate
a key with a value.

You learned some of the important functions that add
and remove items from the dictionary, you learned a
handy way to print the keys and values in a dictionary
in sorted order.
You saw that sorting by key is fairly straightforward,

but sorting by value takes a little more work.


In the next lesson, you’ll learn all about data files,

both reading from them and writing to them.


41
Some exercises:


Write a Python program to count the frequency
in a given dictionary.
Original Dictionary:

{'V': 10, 'VI': 10, 'VII': 40, 'VIII': 20, 'IX': 70, 'X': 80, 'XI': 40, 'XII': 20}

Count the frequency of the said dictionary:


Counter({10: 2, 40: 2, 20: 2, 70: 1, 80: 1})


Write a Python program to find the key of the


maximum value in a dictionary.


Write a Python program to invert a dictionary

with unique hashable values.


42

You might also like