[go: up one dir, main page]

0% found this document useful (0 votes)
9 views34 pages

Wk 6 Python - Dictionaries

The document provides an overview of dictionaries in Python, explaining their structure as key-value pairs and their practical applications. It covers how to create, access, modify, and loop through dictionaries, along with various built-in functions such as keys(), values(), and items(). Additionally, it highlights the ability to add, remove, and check membership of elements within a dictionary.

Uploaded by

valeriecheebb
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)
9 views34 pages

Wk 6 Python - Dictionaries

The document provides an overview of dictionaries in Python, explaining their structure as key-value pairs and their practical applications. It covers how to create, access, modify, and loop through dictionaries, along with various built-in functions such as keys(), values(), and items(). Additionally, it highlights the ability to add, remove, and check membership of elements within a dictionary.

Uploaded by

valeriecheebb
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/ 34

Dictionaries

Juliette Woodrow
Code in Place 2023

Piech + Sahami, CS106A, Stanford University


Learning Goals

1. Learning about dictionaries


2. Building programs using dictionaries

Piech + Sahami, CS106A, Stanford University


Dictionaries

Piech + Sahami, CS106A, Stanford University


What are Dictionaries?

• Dictionaries associate a key with a value


– Key is a unique identifier
– Value is something we associate with that key
• Examples in the real world:
– Phonebook
• Keys: names
• Values: phone numbers
– Dictionary
• Keys: words
• Values: word definitions
– Social Media Platforms
• Keys: usernames
• Values: Information like account details, posts, and followers

Piech + Sahami, CS106A, Stanford University


Dictionaries in Python

• Creating dictionaries
– Dictionary start/end with braces
– Key:Value pairs separated by colon
– Each pair is separated by a comma
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}
squares = {2: 4, 3: 9, 4: 16, 5: 25}
phone = {'Pat': '555-1212', 'Jenny': '867-5309'}
empty_dict = {}

ages 'Chris' 32
'Juliette' 24
'Mehran' 50
Piech + Sahami, CS106A, Stanford University
Accessing Elements of Dictionary
• Consider the following dictionary:
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}

• Like a set of variables that are indexed by keys


ages 'Chris' 32
'Juliette' 24
'Mehran' 50

• Use key to access associated value:


ages['Chris'] is 32
ages['Mehran'] is 50

Piech + Sahami, CS106A, Stanford University


Accessing Elements of Dictionary
• Consider the following dictionary:
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}

• Like a set of variables that are indexed by keys


ages 'Chris' 32
'Juliette' 24
'Mehran' 18

• Use key to access associated value:


ages['Chris'] is 32
ages['Mehran'] is 50
• Can set values like regular variable:
ages['Mehran'] = 18

Piech + Sahami, CS106A, Stanford University


Accessing Elements of Dictionary
• Consider the following dictionary:
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}

• Like a set of variables that are indexed by keys


ages 'Chris' 32
'Juliette' 24
'Mehran' 21

• Use key to access associated value:


ages['Chris'] is 32
ages['Mehran'] is 50
• Can set values like regular variable:
ages['Mehran'] = 18
ages['Mehran'] += 3
Piech + Sahami, CS106A, Stanford University
Accessing Elements of Dictionary
• Consider the following dictionary:
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}

• Like a set of variables that are indexed by keys


ages 'Chris' 32
'Juliette' 24
'Mehran' 21

• Good and bad times with accessing pairs:


>>> chris_age = ages['Chris']
>>> chris_age
32
>>> karels_age = ages['Karel the Robot']
KeyError: 'Karel the Robot'
Piech + Sahami, CS106A, Stanford University
Accessing Elements of Dictionary
• Consider the following dictionary:
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}

• Like a set of variables that are indexed by keys


ages 'Chris' 32
'Juliette' 24
'Mehran' 21

• Checking membership
>>> 'Mehran' in ages
True
>>> 'Karel the Robot' not in ages
True

Piech + Sahami, CS106A, Stanford University


Adding Elements to Dictionary
• Can add pairs to a dictionary:
phone = {}
phone Empty dictionary

Piech + Sahami, CS106A, Stanford University


Adding Elements to Dictionary
• Can add pairs to a dictionary:
phone = {}
phone 'Pat' '555-1212'

phone['Pat'] = '555-1212'

Piech + Sahami, CS106A, Stanford University


Adding Elements to Dictionary
• Can add pairs to a dictionary:
phone = {}
phone 'Pat' '555-1212'
'Jenny' '867-5309'

phone['Pat'] = '555-1212'
phone['Jenny'] = '867-5309'

Piech + Sahami, CS106A, Stanford University


Adding Elements to Dictionary
• Can add pairs to a dictionary:
phone = {}
phone 'Pat' None
'Jenny' '867-5309'

phone['Pat'] = '555-1212'
phone['Jenny'] = '867-5309'
phone['Pat'] = None

Piech + Sahami, CS106A, Stanford University


Adding Elements to Dictionary
• Can add pairs to a dictionary:
phone = {}
phone 'Pat' '867-5309'
'Jenny' '867-5309'

phone['Pat'] = '555-1212'
phone['Jenny'] = '867-5309'
phone['Pat'] = None
phone['Pat'] = '867-5309'

Piech + Sahami, CS106A, Stanford University


Looping Over Dictionary
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}
• Can also loop over a dictionary using for-each loop just
using name of dictionary:
for key in ages:
value = ages[key]
print(str(key) + ' -> ' + str(value))

Terminal:
Chris -> 32
Juliette -> 24
Mehran -> 50

Piech + Sahami, CS106A, Stanford University


Lets Play!

“Mehran Sahami, as a pixar character, reading a dictionary”


Piech + Sahami, CS106A, Stanford University
Lets Play!

“Professor Mehran Sahami, as a pixar character, reading a dictionary”


Piech + Sahami, CS106A, Stanford University
List
index -> value

Piech + Sahami, CS106A, Stanford University


Dictionary
key -> value

Piech + Sahami, CS106A, Stanford University


List Dictionary
my_list = [‘a’, ‘b’, ‘c’] my_dict = {
‘France’: ’+33’,
‘Japan’: ’+81’,
‘Brazil’:’+55’
]

print(my_list[1]) print(my_list[‘France’])

for i in range(len(my_list)): for key in my_dict:


value = my_list[i] value = my_dict[key]
print(i, value) print(key, value)

my_list my_dict

a b c +33 +81 +55


0 1 2 ‘France’ ‘Japan’ ‘Brazil’
indices keysUniversity
Piech + Sahami, CS106A, Stanford
List Dictionary
my_list = [ my_dict = {
‘a’, ‘France’: ’+33’,
‘b’, ‘Japan’: ’+81’,
‘c’ ‘Brazil’:’+55’
] ]

print(my_list[1]) print(my_list[‘France’])

for i in range(len(my_list)): for key in my_dict:


value = my_list[i] value = my_dict[key]
print(i, value) print(key, value)

my_list my_dict

a b c +33 +81 +55


0 1 2 ‘France’ ‘Japan’ ‘Brazil’
indices keysUniversity
Piech + Sahami, CS106A, Stanford
List Dictionary
my_list = [‘a’, ‘b’, ‘c’] my_dict = {
‘France’: ’+33’,
‘Japan’: ’+81’,
‘Brazil’:’+55’
]

print(my_list[1]) print(my_list[‘France’])

for i in range(len(my_list)): for key in my_dict:


value = my_list[i] value = my_dict[key]
print(i, value) print(key, value)

my_list my_dict

a b c +33 +81 +55


0 1 2 ‘France’ ‘Japan’ ‘Brazil’
indices keysUniversity
Piech + Sahami, CS106A, Stanford
List Dictionary
my_list = [‘a’, ‘b’, ‘c’] my_dict = {
‘France’: ’+33’,
‘Japan’: ’+81’,
‘Brazil’:’+55’
]

print(my_list[1]) print(my_list[‘France’])

for i in range(len(my_list)): for key in my_dict:


value = my_list[i] value = my_dict[key]
print(i, value) print(key, value)

my_list my_dict

a b c +33 +81 +55


0 1 2 ‘France’ ‘Japan’ ‘Brazil’
indices keysUniversity
Piech + Sahami, CS106A, Stanford
List Dictionary
my_list = [‘a’, ‘b’, ‘c’] my_dict = {
‘France’: ’+33’,
‘Japan’: ’+81’,
‘Brazil’:’+55’
]

print(my_list[1]) print(my_list[‘France’])

for i in range(len(my_list)): for key in my_dict:


value = my_list[i] value = my_dict[key]
print(i, value) print(key, value)

my_list my_dict

a b c +33 +81 +55


0 1 2 ‘France’ ‘Japan’ ‘Brazil’
indices keysUniversity
Piech + Sahami, CS106A, Stanford
List Dictionary
my_list = [‘a’, ‘b’, ‘c’] my_dict = {
‘France’: ’+33’,
‘Japan’: ’+81’,
‘Brazil’:’+55’
]

print(my_list[1]) print(my_list[‘France’])

for i in range(len(my_list)): for key in my_dict:


value = my_list[i] value = my_dict[key]
print(i, value) print(key, value)

my_list my_dict

a b c +33 +81 +55


0 1 2 ‘France’ ‘Japan’ ‘Brazil’
indices keysUniversity
Piech + Sahami, CS106A, Stanford
More Dictionary Fun! (Part 1)
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}
• Function: dict.keys()
– Returns something similar to a range of the keys in dictionary
– Can use that to loop over all keys in a dictionary:
for key in ages.keys():
print(str(key) + " -> " + str(ages[key]))
Terminal:
Chris -> 32
Juliette -> 24
Mehran -> 50

– Can turn keys() into a list, using the list function


>>> list(ages.keys())
['Chris', 'Juliette', 'Mehran']

Piech + Sahami, CS106A, Stanford University


More Dictionary Fun! (Part 2)
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}
• Function: dict.values()
– Returns something similar to a range of the values in dictionary
– Can use that to loop over all keys in a dictionary:
for value in ages.values():
print(value)
Terminal:
32
24
50

– Can turn values() into a list, using the list function


>>> list(ages.values())
[32, 24, 50]

Piech + Sahami, CS106A, Stanford University


More Dictionary Fun! (Part 3)
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}
• Function: dict.items()
– Returns
– Can use that to loop over all key value pairs in a dictionary:
for key, value in ages.items():
print(f"{key}, {value}")
Terminal:
Chris, 32
Juliette, 24
Mehran, 50

Piech + Sahami, CS106A, Stanford University


More Dictionary Fun! (Part 4/5)
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}
• Function: dict.pop(key)
– Removes key/value pair with the given key. Returns value from
that key/value pair.
>>> ages
>>> {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}
>>> ages.pop('Mehran')
50
>>> ages
{'Chris': 32, 'Juliette’: 24}
• Function: dict.clear()
– Removes all key/value pairs in the dictionary.
>>> ages.clear()
>>> ages
{}
Piech + Sahami, CS106A, Stanford University
Functions You Can Apply
ages = {'Chris': 32, 'Juliette’: 24, 'Mehran': 50}
• Function: len(dict)
– Returns number of key/value pairs in the dictionary
>>> ages
{'Chris': 32, 'Juliette’: 24, 'Mehran': 50}
>>> len(ages)
3
• Function: del dict[key]
– Removes key/value pairs in the dictionary.
– Similar to pop, but doesn't return anything.
>>> ages
{'Chris': 32, 'Juliette’: 24, 'Mehran': 50}
>>> del ages['Mehran']
>>> ages
{'Chris': 32, 'Juliette’: 24}
Piech + Sahami, CS106A, Stanford University
Example:
count_nums.py

Piech + Sahami, CS106A, Stanford University


Example:
phonebook.py

Piech + Sahami, CS106A, Stanford University


Learning Goals

1. Learning about dictionaries


2. Building programs using dictionaries

Piech + Sahami, CS106A, Stanford University

You might also like