Week 8

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Week 8

Structured Types – tuples, dictionaries


Structured Types: tuples

Tuples are an ordered sequence of elements, which may contain a mix of


element types
Tuples are immutable, you cannot change element values
Tuples are represented using parentheses ( )

2
Example with Tuples
#create an empty tuple
t1 = ()
Output:
()
#create a tuple containing 3 values
(1, 'Two', 3)
t2 = (1,"Two", 3)
Two
<class 'str’>
#display the tuples
print(t1)
print(t2)

#display an element in a tuple


print( t2[1] )

#display the type of the element


print( type(t2[1]))

#tuples are immutable


#t2[0] = 5 -> TypeError: 'tuple' object does not support item assignment
3
Structured Types: tuples
Like strings, tuples can be concatenated, indexed and sliced.

#concatenating tuples Output:


t1 = ( 'a', 'b', 5) ('a', 'b', 5, 7)
t2 = (7,) 5
t1 = t1 + t2 ('b', 5)
print(t1)

#indexing with tuples


print(t1[2])

#slicing tuples
print(t1[1:3]) 4
Exercises with Tuples

Write a python script that creates two tuples, one that contains the names of the G8
countries, and one that contains the top 10 countries to live in.

• Your script should find the common countries and store in a new tuple.

• Update your script to also find and store in a tuple all countries from both groups
(no duplicates).

See: common_countries.py

5
Dictionaries
• A dictionary is a container that stores
associations between keys and values. key1 value1
• Also known as a map, because it maps key2 value2
unique keys to values.
key3 value3
• Every key is associated with a value.
• Keys must be unique in a dictionary. … …
• Values can be duplicated, but each value keyN valueN
will be associated with a unique key.

6
Creating Dictionaries

Dictionary objects are created using curly braces { }


Syntax:
dict = {key1 : value1, key2 : value2, … keyN : valueN }
You can create an empty dictionary, using empty braces.
dict = {}
Example:
#create a dictionary
phone = { 'Evren':7445167, 'Ana':6413354,'Enes':6543210}

7
Accessing Dictionary Values
The subscript operator([ ]) is used to return the Example:
value associated with a key. phone = { 'Evren':7445167,
'Ana':6413354,
'Enes':6543210}
Dictionary is not a sequence-type container like a name = input('Enter name to search: ')
list so although the subscript operator is used, you
cannot access the items by numeric if name in phone:
print(name,"'s number is:",phone[name])
index/position. else:
print(name,' not in dictionary')
The given key must be in the dictionary, if it is not,
a KeyError will be raised. Use in/not in to
check if key values exist before accessing.

Syntax:

dict[ key ] -> returns the value associated


with a given key.
8
Adding/Updating Values

Dictionaries are mutable, you can change its contents after it has been created.

To change a value associated with a given key, set a new value using the [ ] operator on
an existing key.

dict[key]= new_value

To add items to the dictionary, just specify the new value using a new unique key:

dict[new_key]= new_value

9
Example with Adding/Updating
name = input('Enter person to update: ')
number = input('Enter phone number: ')
if name in phone:
phone[name] = number
print(name, 'updated! (', phone[name],')')
else:
phone[name] = number
print(name, 'added! (', phone[name],')')

10
Removing Items – pop( )
To remove a key / value pair from the dictionary, you can use the pop() function.
Syntax:
dict.pop( key ) -> removes the key/value pair with the given key.
Example:
#remove keys from dictionary
name = input('Enter person to remove: ')
if name in phone:
phone.pop(name)
print(name, 'removed! ')
else:
print(name, 'not in phone book') 11
Traversing a Dictionary (Iteration)
You can iterate over the individual keys in a dictionary using a for loop.

Example:
#traversing a dictionary
print('Contact List: ')
for people in phone:
print(people,phone[people])

Note: the above example is used to show iteration through the elements in a dictionary, but
it can also be done without using a for loop.
12
Dictionary Function Summary

Function Purpose
len(d) Returns the number of items in d.
d.keys() Returns a view of the keys in d.
d.values() Returns a view of the values in d.
k in d Returns true if k is in d.
d[k] Returns the item in d with key k.
d.get(k,v) Returns d[k] if k is in d, v otherwise.
d[k] = v Associates the value v with the key k in d, if there is already a
value associated with k, that value is replaced.
d.pop(k) Removes the key/value pair with the given key, k in d.
for k in d Iterates over the keys in d.

13
Exercise - Dictionaries

Write a script that does the following:


• creates a dictionary of cars, where the key values are the brands, and the values are the
country of origin.
('Toyota':'Japan','Volkswagen':'Germany','Honda':'Japan','BMW':'Germany','Volvo':'Sweden')

• Inputs a brand from the user and displays the country of the given brand.
• Inputs a country from the user and displays the car brands from the given country.

See: car_dictionary.py
14

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy