Docsity

Python Lesson on Dictionaries and Tuples, Study notes of Advanced Computer Programming

Partial preview of the text

Download Python Lesson on Dictionaries and Tuples and more Study notes Advanced Computer Programming in PDF only on Docsity!

Python Lesson –

Dictionaries

Image Source: https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSVkMx0ulre7iqizJ6FHgrwy2fjXrsuORsm5R9gq- caIe3pJHXa

Lesson Description

In this lesson, we will be learning about a new data structure—the dictionary. The dictionary

(also known as a hashtable or hashmap in other languages) is one of the most powerful data

structures Python has available to use. Luckily, since it’s built in to the Python language, we

don’t have to implement it ourselves. We will also be learning about tuples. We have briefly

introduced them previously, but will now do so more explicitly and make use of them along with

the Dictionary.

What you will learn:

  • How to use a Dictionary Data Structure
  • How to use Tuples

Getting Setup

In this lesson, we are going to be working in the Python Idle editor as well as the terminal. We

will learn about the dictionary in the Idle editor, and then we are going to graduate to creating

our own files and working with data.

Our Second Major Data Structure – The Dictionary

The list has been the focus of most of our discussion previously, but now it is time to use

another powerful data structure. The Dictionary is a powerful data structure that has a ‘key’ and

a ‘value’. Each key is unique in the dictionary, and it has an associated value. The associated

value however, does not need to be unique.

Examples of dictionaries in real life include:

o A phone book:

o Key – The phone number

o Value – The persons name

o A physical dictionary (hence where the name of this data structure comes from)

o Key – The word

o Value – The description of the word (i.e. the definition).

o A Student identification number at a university

o Key – the number

o Value – The persons name

o Your Subway Loyalty Card:

o Key – Your card number

o Value – Your points you’ve amassed!

The key in the dictionary can be a string or a number. In fact, it can be any data type! The

takeaway though is that the key must be unique!

Here’s a look at some sample tables of the above examples to again illustrate keys and values.

Key (Phone Number) Value (Persons Name)

7323245 ‘Joe’

However, we can also use a name as a key, because it is typically easier for us to remember a

persons name.

phoneBook = {‘Mike’: 55555555} # ‘Mike’ is the key

In this example, we can only have one friend named Mike. If we want more Mike’s, we’d have to

store them as Mike01, Mike02, Mike03, etc.

We can print out a specific entry from our phonebook using the following:

print phoneBook[‘Mike’]

If we want to output the entire contents of the phonebook, we can simply use the print

command.

Print phoneBook

print phoneBook

Over time, we will want to grow and modify our dictionary, so we can add entries like the

following.

Add a new item

phoneBook[‘Michelle’] = 43255322

Lets confirm our entry went in.

print phoneBook

Delete Mike from our phonebook, we’ll never need to call him!

del phoneBook[‘Mike’]

If Michelle changes her number, we can update it by accessing her

entry with her key (‘Michelle’) and then simply re-assigning a new value. phoneBook[‘Michelle’] = 3252352

Confirm our changes have been made.

print phoneBook

Sometimes we are not sure who is in our phonebook, so we have to

iterate over all of # the keys. When we know what keys are available,

we can then use those keys to quickly index into our phone book and

retrieve the value (a phone number in this case).

print keys

for x in phoneBook: print x

Alternatively, if we just need the numbers, we can print out all of

the values.

This might be a nice thing to do if you want to call everyone and

wish them a happy

new year.

This might be an evil thing to do if you want to call everyone and

try to scam them!

Look out!

print values

for x in phoneBook: print phoneBook[x] ANOTHER LOOK AT THE DICTIONARY

The dictionary is what is known as an ‘associative data structure’. This means that a value is

associated with a key. Great, that makes perfect sense! This should be intuitive, because this is

often how our brain works. We generally do not think of a number and say, oh that is Mike’s

number. We generally think of a name (e.g. ‘Mike’), and then recall what his number is. Our

brains work very well by associating one thing with the next, so it should not be a surprise we

can do something similar with computers.

THE TUPLE

The Tuple is a way in Python to group information together. It is like a list, except that we cannot

modify it once we have created a tuple.

Lets go ahead and create a tuple that groups together information about an individual.

Lets create a Person Tuple that will take a str, and an int as the two types of data we want to

store. The first value is a string storing a name, and the second is an integer value for how

many miles they ran this month.

So the tuple itself is just a collection of values held together. We can actually store tuples in a

list if we want. Lets create some more tuples with names and each persons favorite number as

a value in a second field.

Shaquille O’Neil (4,19)

Mike Shah (0,0)

Example:

Creating a tuple.

samJones = (10,12)

This makes the variable ‘samJones’ hold the tuple (10,12).

We then want to put all of these players (or rather, their tuples) into a dictionary, and then output

all of the NBA players who have won at least 1 championship.

Here is an example of creating an empty dictionary, and adding our player to it.

Now lets create an empty dictionary

nbaDictionary = {}

Add a key of ‘Sam Jones’ and a

value of samJones (which is a tuple)

nbaDictionary['Sam Jones'] = samJones

Goals we want to achieve:

  • Output all NBA players in our dictionary who have won at least one championship
  • Output all of the NBA players in our dictionary who have won a championship in greater

in 50% of the seasons they have played.

Hints and gotchas:

  • print out your dictionary after you input your entries to visually see the data.
  • Can we divide by zero in mathematics?
  • Use an ‘and’ statement to check two conditions.

o e.g. if value > 5 and value != 0:

  • When dividing two integers, we get an integer back. If we want a float (i.e. decimal

number) as a result, we have to divide to floats.

o Example:

THE CORRECT OUTPUT

The correct output is below and the solution follows in the next section.

If you want to take this problem even further you can add the following items.

GOING FURTHER

  • Create your own query on the dictionary.

o Add all of the players to a list who have won championships in at least half of the

seasons that they have played.

o Make a function that adds a players name and value into the dictionary (this will

save many lines of code).

§ Make up some more players to add to the list.

§ Create an interactive prompt that allows you to choose 5 players from the

dictionary, and add them to a list, to assemble your all-star NBA team!