Complex types Dictionaries Upsorn Praphamontripong CS 1110 Introduction to Programming Spring 2017 Overview Dictionaries 2 CS 1110 Dictionary unordered sequence of data Mutable ID: 550606
Download Presentation The PPT/PDF document "Data types:" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Data types:Complex types (Dictionaries)
Upsorn
Praphamontripong
CS 1110
Introduction to Programming
Spring 2017Slide2
Overview: Dictionaries2
CS 1110
Dictionary =
unordered
sequence of data
Mutable
data type
Each element in a dictionary consists of 2 parts: key and value
Key-value pair
Key = index to locate a specific value
Deterministic:
A particular input(
key
) can only have one output (
value
)
Example: key = student ID, value = student nameSlide3
Lists vs Dictionaries
3
CS 1110
Complex type
Mutable
Ordered sequence of data
Index = 0, 1, 2,
…
Complex type
Mutable
Unordered sequence of dataIndex = user-defined key
Lists
Dictionaries
keys
values
index
values
0
1
2 Slide4
Dictionaries 4
CS 1110
phonebook
= {'
george
':
'111-1111', '
tom'
:'222-
2222'}
keyvalue
Create a dictionary
phonebook['tom']
Retrieve
a
value
from
a
dictionary
Include quotations for string keysWhat would happen if we try to access an index that doesn’t exist?
phonebook2 = { }Empty dictionarySlide5
Add Items to a Dictionary5
CS 1110
phonebook =
{
'
george
':
'111-1111', 'Chris':'222-2222', 'Tom':'333-3333'
}
phonebook['Joe'] = '444-
4444’
Dictionary_name[key] = valueNo duplicate keys in a dictionaryWhen you assign a value to an existing key, the new value replaces the existing valueassignmentkey
valueSlide6
Delete Items from Dictionaries6
CS 1110
del
phonebook['Chris']
del
deletes an element at a particular position
What would happen
if we try to
delete an item with an
index that doesn’t exist?
key
pop()
gets a value (and use it somewhere else), and deletes an element (a key/value pair)
phone_number
=
phonebook.pop
(
'
Chris'
)keySlide7
Length of Dictionaries7
CS 1110
phonebook
=
{
'
george
':
'111-1111', 'Chris':'222-2222', 'Tom':'333-3333'}
num_items
= len(phonebook)
len() is a function to return the length of a dictionary (i.e., the number of items in a dictionary)Slide8
Retrieve Values, Keys, or Items8
CS 1110
phonebook.get
("
Joe”)
#
retrieve a value for a particular
key
phonebook.get
("Tim", "
Not available") # try to access a non-existent keyphonebook.items() # retrieve all the keys and values phonebook.keys() # retrieve all the available keysphonebook.values() # retrieve all the values
get() gets a particular value based on keyitems() gets all the keys and valueskeys() gets all the keys
values() gets all the valuesSlide9
Mix Data Types in Dictionaries9
CS 1110
test_scores
= {'Tom' : [88, 92, 100]
, '
John' : [95, 88, 81],
'
Ethan' : [70, 75, 78]
}
print(test_scores)print('John\'s scores : ' + str(test_scores['John'])) # why do we need str()?Ethan_scores = test_scores['Ethan']print('Ethan\'s scores : ' + str(Ethan_scores))
Keys must be immutable Values can be of any data typesSlide10
in10
CS 1110
phonebook
=
{
'
george
':
'111-1111', 'Chris':'222-2222', 'Tom':'333-3333'}
phonebook['Joe'] = '444-
4444’print("Joe" in phonebook)print("Joe" not in phonebook)print("Joe" in phonebook.keys())print("444-4444" in phonebook.values())
in is a keyword and can be used to check if a particular item/key/value is in the dictionary/keys/values before trying to get its indexSlide11
Empty the Dictionaries11
CS 1110
p
honebook.clear
()
clear()
empties the dictionarySlide12
2
1
0
Tracing through Code with
Dictionaries
12
CS 1110
numAnimals
= {}
numAnimals
[‘
cat
’] = 3
numAnimals
[‘fish’] = 22
numAnimals[‘dog’] = 5
Variables
Heap
A100
numAnimals
A100
Suppose
we are using a dictionary to keep
track of the number of animals in a small pet store
22
5
3
‘fish’
‘dog’
‘cat’
5
22
3
dog
fish
cat
keys
valuesSlide13
Tracing through Code with Dictionaries13
CS 1110
numAnimals
= {}
numAnimals
[‘
cat
’] = 3
numAnimals
[‘
fish’] = 22numAnimals[‘dog’] = 5print numAnimals[‘dog’]print numAnimals[2]print numAnimals.keys()print numAnimals.values()
VariablesHeap
A100
numAnimals
A100
22
Suppose
we
are
using
a dictionary to keep
track of the number of animals in a small pet store
5
3
‘fish’
‘dog’
‘cat’
A100 of ‘dog’
5
A100 of 2
error
keys
values
[‘cat’, ‘dog’, ‘fish’]
[3, 5, 22]Slide14
Tracing through Code with Dictionaries14
CS 1110
numAnimals
= {}
numAnimals
[‘
cat
’] = 3
numAnimals
[‘
fish’] = 22numAnimals[‘dog’] = 5print numAnimals[‘dog’]print numAnimals.keys()print numAnimals.values()numAnimals[‘bird’] = 4numAnimals[‘cat’] = 2
VariablesHeap
A100
numAnimals
A100
Suppose
we
are
using
a dictionary
to keep track of the number of animals in a small pet store
22
5
3
‘fish’
‘dog’
‘cat’
keys
values
4
‘bird’
A100 of ‘cat’
2Slide15
Dictionaries (wrap up)15
CS 1110
declare a dictionary with curly braces
add to a
dict
by specifying a key and assigning it a value
a key must be immutable (no lists)
the .keys() method returns all the keys (but we can’t rely on an order)
the .values() method returns all the values (but we can’t rely on an order)
assigning to a key that already has that value overwrites the old value
dict = {}dict[1] = 'cat'dict['dog'] = -8dict[False] = 'squirrel’print(dict.keys())print(dict.values
())print(dict)if 'dog' in dict.keys(): print('dog has a mapping!')if 'cat' in dict.keys(): print('cat has a mapping!')dict['dog'] = 5print(dict)Slide16
Exercise16
CS 1110
Create a dictionary of an “experience” object.
You will start by getting inputs from users. Inputs contain
The name of the experience (e.g., "software engineer”)
The company of the experience (e.g., “IBM”)
The year of the experience (e.g., “1996”)
Add the users’ inputs to an “experience” dictionary
The
keys
in the dictionary will be the year of the experience, while the values will be the name of the experience and the companies, stored as a list. E.g., { ‘1996’ : [‘software engineer’, ‘IBM], ‘1993’ : [‘sale’, ‘Target’] }You should get at least 2 experience inputs from the users. Print each experience in a separate lineYou may assume that all experiences passed in as arguments never have two experiences with the same company and year. Try to add more actions: retrieve items, delete items, update items, …