0% found this document useful (0 votes)
50 views14 pages

Week 8: Structured Types - Lists, Tuples, Dictionaries

This document discusses structured types in Python, including tuples and dictionaries. Tuples are immutable ordered sequences that use parentheses. Dictionaries are mutable containers that map unique keys to values using curly braces. Keys in a dictionary must be unique, while values can be duplicated. The document provides examples of creating, accessing, adding, updating, and removing items from tuples and dictionaries. Exercises are included to practice working with these data types.

Uploaded by

Kemalhan Aydın
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)
50 views14 pages

Week 8: Structured Types - Lists, Tuples, Dictionaries

This document discusses structured types in Python, including tuples and dictionaries. Tuples are immutable ordered sequences that use parentheses. Dictionaries are mutable containers that map unique keys to values using curly braces. Keys in a dictionary must be unique, while values can be duplicated. The document provides examples of creating, accessing, adding, updating, and removing items from tuples and dictionaries. Exercises are included to practice working with these data types.

Uploaded by

Kemalhan Aydın
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/ 14

Week 8

Structured Types – lists, 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 ( )


Example with Tuples
#create an empty tuple
t1 = ()
Output:
()
#create a tuple containing 3 values
(1, 'Two', 3)
t2 = (1,"Two", 3)
Two
#display the tuples
<class 'str’>
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
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])
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
Dictionaries

A dictionary is a container that stores associations between keys and values.


Also known as a map, because it maps unique keys to values.

Every key is associated with a value.

Keys must be unique in a dictionary.

Values can be duplicated, but each value will be associated with a unique
key.
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}
Accessing Dictionary Values
The subscript operator([]) is used to return the value Example:
associated with a key. phone = { 'Evren':7445167,
'Ana':6413354,
'Enes':6543210}
Dictionary is not a sequence-type container like a list so name = input('Enter name to search: ')
although the subscript operator is used, you cannot access the
if name in phone:
items by index/position. print(name,"'s number is:",phone[name])
else:
The given key must be in the dictionary, if it is not, a KeyError print(name,' not in dictionary')

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.
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
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],')')
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')
Traversing a Dictionary (Iteration)
The dictionary stores its items in an order that is optimized for efficiency, which may not be
the order in which they were added.
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.
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.
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

You might also like