A dictionary is similar to a list, but the order of items doesn't matter, and they aren't selected by an offset such as 0 or 1.
Instead, we specify a unique key to associate with each value.
This key is often a string, but it can actually be any of Python's immutable types: boolean, integer, float, tuple, string, and others.
Dictionaries are mutable, so we can add, delete, and change their key-value elements.
Create with {}
{}
) around comma-separated key : value pairs.empty_dict = {}empty_dict
Let's make a small dictionary with quotes from Ambrose Bierce's The Devil's Dictionary:
bierce = {"day": "A period of twenty-four hours, mostly misspent", "positive": "Mistaken at the top of one's voice", "misfortune": "The kind of fortune that never misses"}bierce
Create with dict()
dict()
function.acme_customer = {'first': 'Wile', 'middle': 'E', 'last': 'Coyote'}acme_customeracme_customer = dict(first = "Wile", middle = "E", last = "Coyote")acme_customer
dict()
need to be legal variable names (no spaces, no reserved words):x = dict(name="Elmer", def="hunter")
Convert with dict()
dict()
to convert two-value sequences into a dictionary.lol = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ]dict(lol)
lot = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]dict(lot)
tol = ( ['a', 'b'], ['c', 'd'], ['e', 'f'] )dict(tol)
los = [ 'ab', 'cd', 'ef' ]dict(los)
tos = ( 'ab', 'cd', 'ef' )dict(tos)
Add or Change an Item by [ key ]
Adding an item to a dictionary is not complicated.
Just refer to the item by its key and assign a value.
If the key was already present in the dictionary, the existing value is replaced by the new one.
If the key is new, it's added to the dictionary with its value.
Add or Change an Item by [ key ]
st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver' }st_city
st_city['NY'] = 'Rocjester'st_city
st_city['NY'] = 'Rochester'st_city
city_st = { 'Rochester': 'MN', 'Laramie': 'WY', 'Denver': 'CO', 'Rochester': 'NY' }city_st
Get an Item by [key]
or with get()
city_st = { 'Rochester': 'MN', 'Laramie': 'WY', 'Denver': 'CO', 'Rochester': 'NY' }city_st['Denver']
city_st['Buffalo']
in
and get()
in
:'Buffalo' in city_st
get()
function.city_st.get('Denver')
get()
function.city_st.get('Buffalo', 'Not in city_st')
get()
function.None
, which displays nothing in the console.city_st.get('Buffalo')
Get All Keys with keys()
keys()
to get all of the keys in a dictionary. signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.keys()list( signals.keys() ) # to turn the result into a list object.
Get All Values with values()
values()
:signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.values()list( signals.values() ) # to turn the result into a list object.
Get All Key-Value Pairs with items()
items()
function:signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.items()list( signals.items() ) # to turn the result into a list object.
Get Length with len()
signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}len(signals)
Combine Dictionaries with {**a, **b}
**
:first = {'a': 'agony', 'b': 'bliss'}second = {'b': 'bagels', 'c': 'candy'}{**first, **second}third = {'d': 'donuts'}{**first, **third, **second}
Combine Dictionaries with update()
update()
function to copy the keys and values of one dictionary into another.st_city
with other_city
st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }other_city = {'MA': 'Boston'}st_city.update(other_city)
Combine Dictionaries with update()
first = {'a': 1, 'b': 2}second = {'b': 'platypus'}first.update(second)first
Delete an Item by Key with del
del
:del st_city['NY']st_city
Get an Item by Key and Delete It with pop()
pop()
combines get()
and del
. pop()
a key and it exists in the dictionary, it returns the matching value and deletes the key-value pair. pop()
a second default argument, all is well and the dictionary is not changed:len(st_city)st_city.pop('MN') # Check len(st_city)st_city.pop('MN') # If it doesn't exist, it raises an exception:st_city.pop('MN', 'Not exist')
Delete All Items with clear()
clear()
or just reassign an empty dictionary ({}
) to the name:st_city.clear()st_cityst_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }st_city = {}st_city
Test for a Key with in
in
:st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }'NY' in st_city'WY' in st_city'CA' in st_city
Assign with =
signals = { 'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera' }save_signals = signalssignals['blue'] = 'confuse everyone'signals
save_signals
now? Copy with copy()
copy()
:signals = { 'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera' }original_signals = signals.copy()signals['blue'] = 'confuse everyone'signals
original_signals
now? Copy Everything with deepcopy()
signals
was a list instead of a single string:signals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_copy = signals.copy()signals
signals_copy
? Copy Everything with deepcopy()
signals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_copy = signals.copy()signals['red'][1] = 'sweat'signals
signals_copy
? Copy Everything with deepcopy()
deepcopy()
:import copysignals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_deepcopy = copy.deepcopy(signals)signalssignals_deepcopysignals['red'][1] = 'sweat'signals
signals_deepcopy
?Compare Dictionaries
==
and !=
:a = {1:1, 2:2, 3:3}b = {3:3, 1:1, 2:2}a == ba != ba <= b # does it work?
Iterate with for
and in
keys()
function) returns the keys. accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for card in accusation: # or, for card in accusation.keys(): print(card)
Iterate with for
and in
values()
function:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for value in accusation.values(): print(value)
Iterate with for
and in
items()
function:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for item in accusation.items(): print(item)
Iterate with for
and in
items()
, let's assign the first value (the key) to card, and the second (the value) to contents:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for card, contents in accusation.items(): print('Card', card, 'has the contents', contents)
Dictionary Comprehensions
Dictionary Comprehensions
word = 'letters'letter_counts = {letter: word.count(letter) for letter in word}letter_counts
Dictionary Comprehensions
word = 'letters'letter_counts = {letter: word.count(letter) for letter in set(word)}letter_counts
Dictionary Comprehensions
vowels = 'aeiou'word = 'onomatopoeia'vowel_counts = {letter: word.count(letter) for letter in set(word) if letter in vowels}vowel_counts
A set is like a dictionary with its values thrown away, leaving only the keys.
We use a set when we only want to know that something exists, and nothing else about it.
Common things to do with sets
Create with set()
set()
function or enclose one or more comma-separated values in curly brackets:empty_set = set()empty_seteven_numbers = {0, 2, 4, 6, 8}even_numbersodd_numbers = {1, 3, 5, 7, 9}odd_numbers
Convert with set()
set( 'letters' ) set( ['Dasher', 'Dancer', 'Prancer', 'Mason-Dixon'] )set( ('Ummagumma', 'Echoes', 'Atom Heart Mother') )set( {'apple': 'red', 'orange': 'orange', 'cherry': 'red'} )
Get Length with len()
reindeer = set( ['Dasher', 'Dancer', 'Prancer', 'Mason-Dixon'] )len(reindeer)
Add an Item with add()
add()
methods = set((1,2,3))ss.add(4)s
Delete an Item with remove()
s = set((1,2,3))s.remove(3)s
Iterate with for
and in
furniture = set(('sofa', 'ottoman', 'table'))for piece in furniture: print(piece)
Test for a Value with in
drinks
. drinks = { 'martini': {'vodka', 'vermouth'}, 'black russian': {'vodka', 'kahlua'}, 'white russian': {'cream', 'kahlua', 'vodka'}, 'manhattan': {'rye', 'vermouth', 'bitters'}, 'screwdriver': {'orange juice', 'vodka'} }
for name, contents in drinks.items(): if 'vodka' in contents: print(name)
cream
nor vermouth
but do vodka
:for name, contents in drinks.items(): if 'vodka' in contents \ and not ('vermouth' in contents or 'cream' in contents): print(name)
Combinations and Operators
drinks = { 'martini': {'vodka', 'vermouth'}, 'black russian': {'vodka', 'kahlua'}, 'white russian': {'cream', 'kahlua', 'vodka'} }bruss = drinks['black russian']wruss = drinks['white russian']a = {1, 2}b = {2, 3}
&
. intersection()
function does the same.a & ba.intersection(b)bruss & wruss
|
or the set union()
function:a | ba.union(b)bruss | wruss
-
or the difference()
function:a - ba.difference(b)bruss - wrusswruss - bruss
^
or symmetric_difference()
:a ^ ba.symmetric_difference(b)bruss ^ wruss
<=
or issubset()
:a <= ba.issubset(b)bruss <= wrussa <= a # any set is a subset of itself?a.issubset(a)
<
:a < bb < abruss < wruss
>=
or issuperset()
:a >= ba.issuperset(b)wruss >= brussa >= a # any set is a superset of itself?a.issuperset(a)
>
:a > bwruss > brussa > a
&
):for name, contents in drinks.items(): if contents & {'vermouth', 'orange juice'}: print(name)
for name, contents in drinks.items(): if 'vodka' in contents and not contents & {'vermouth', 'cream'}: print(name)
Set Comprehensions
a_set = {number for number in range(1,6) if number % 3 == 1}
Create an Immutable Set with frozenset()
frozenset()
function with any iterable argument:frozenset([3, 2, 1])frozenset(set([2, 1, 3]))frozenset({3, 1, 2})frozenset( (2, 3, 1) )fs = frozenset([3, 2, 1])fsfs.add(4)
[]
)()
){}
)marx_list = ['Groucho', 'Chico', 'Harpo']marx_tuple = ('Groucho', 'Chico', 'Harpo')marx_dict = {'Groucho': 'banjo', 'Chico': 'piano', 'Harpo': 'harp'}marx_set = {'Groucho', 'Chico', 'Harpo'}
marx_list[2]marx_tuple[2]marx_dict['Harpo']'Harpo' in marx_set
We can combine these built-in data structures into bigger, more complex structures of our own.
Let's start with three different lists:
newyork = ['Geneseo', 'Rochester', 'Buffalo']california = ['San Francisco', 'Los Angeles', 'San Diego']texas = ['Dallas', 'Houston', 'Austin']
tuple_of_lists = newyork, california, texastuple_of_lists
list_of_lists = [newyork, california, texas]list_of_lists
dict_of_lists = {'NY': newyork, 'CA': california, 'TX': texas}dict_of_lists
Class Exercises
1. Make an English-to-French dictionary called e2f
and print it. Here are your starter words: dog
is chien
, cat
is chat
, and walrus
is morse
.
2. Using your three-word dictionary e2f
, print the French word for walrus
.
3. Make a French-to-English dictionary called f2e
from e2f
Use the items
method.
4. Print the English equivalent of the French word chien
.
5. Print the set of English words from e2f
.
Class Exercises
6. Make a multilevel dictionary called life
. Use these strings for the topmost keys: 'animals
', 'plants
', and 'other
'. Make the 'animals' key refer to another dictionary with the keys 'cats
', 'octopi
', and 'emus
'. Make the 'cats
' key refer to a list of strings with the values 'Henri
', 'Grumpy
', and 'Lucy
'. Make all the other keys refer to empty dictionaries.
7. Print the top-level keys of life
.
8. Print the keys for life['animals']
.
9. Print the values for life['animals']['cats']
.
Class Exercises
10. Use a dictionary comprehension to create the dictionary squares
. Use range(10)
to return the keys, and use the square of each key as its value.
11. Use a set comprehension to create the set odd
from the odd numbers in range(10)
.
Define a Function with def
To define a Python function, we type def
, the function name, parentheses enclosing any input parameters to the function, and then finally, a colon (:).
Function names have the same rules as variable names (they must start with a letter or and contain only letters, numbers, or ).
def do_nothing(): pass # indention is needed here
pass
statement when we want Python to do nothing.do_nothing()
function just by typing its name and parentheses. do_nothing()
Call a Function with Parentheses
def make_a_sound(): print('quack') make_a_sound()
def agree(): return True
agree()
function and test its returned value by using if
:if agree(): print('Splendid!')else: print('That was unexpected.')
Arguments and Parameters
echo()
with one parameter called anything
.return
statement to send the value of anything back to its caller twice, with a space between:def echo(anything): return anything + ' ' + anythingecho('Geneseo')
The values we pass into the function when we call it are known as arguments.
When we call a function with arguments, the values of those arguments are copied to their corresponding parameters inside the function.
Arguments and Parameters
def echo(anything): return anything + ' ' + anythingecho('Geneseo')
The function echo()
was called with the argument string 'Geneseo'
.
'Geneseo'
was copied within echo()
to the parameter anything
, and then returned (in this case doubled, with a space) to the caller.Arguments and Parameters
commentary
, have it take an input string parameter
called color
, and make it return the string description to its caller:def commentary(color): if color == 'red': return "It's a tomato." elif color == "green": return "It's a green pepper." elif color == 'bee purple': return "I don't know what it is, but only bees can see it." else: return "I've never heard of the color " + color + "."
Arguments and Parameters
commentary()
with the string argument 'blue'
.comment = commentary('blue')
'blue'
to the function's internal color parameterif-elif-else
logic chaincomment
.print(comment)
A function can take any number of input arguments (including zero) of any type.
It can return any number of output results (also including zero) of any type.
return
explicitly, the caller gets the result None
.def do_nothing(): passprint(do_nothing())
None
Is Useful
None
is a special Python value that holds a place when there is nothing to say.
False
, although it looks false when evaluated as a boolean. thing = Noneif thing: print("It's some thing")else: print("It's no thing")
None
from a boolean False
value, use Python's is
operator:thing = Noneif thing is None: print("It's some thing")else: print("It's no thing")
None
to distinguish a missing value from an empty value.''
), lists ([]
), tuples ((,)
), dictionaries ({}
), and sets (set()
) are all False
, but are not the same as None
.None
, True
, or False
:def whatis(thing): if thing is None: print(thing, "is None") elif thing: print(thing, "is True") else: print(thing, "is False")
whatis(None)whatis(True)whatis(False)
whatis(0)whatis(0.0)whatis('')whatis("")whatis('''''')whatis(())whatis([])whatis({})whatis(set())
whatis(0.00001)whatis([0])whatis([''])whatis(' ')
Positional Arguments
The most familiar types of arguments are positional arguments, whose values are copied to their corresponding parameters in order.
This function builds a dictionary from its positional input arguments and returns it:
def menu(wine, entree, dessert): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('chardonnay', 'chicken', 'cake')
Positional Arguments
menu('beef', 'bagel', 'bordeaux')
Keyword Arguments
menu(entree='beef', dessert='bagel', wine='bordeaux')# Specify the wine first, but use keyword arguments for the entree and dessert:menu('frontenac', dessert='flan', entree='fish')
Specify Default Parameter Values
menu()
without the dessert
argument:def menu(wine, entree, dessert='pudding'): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('chardonnay', 'chicken')
def menu(wine, entree, dessert='pudding'): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('dunkelfelder', 'duck', 'doughnut')
Specify Default Parameter Values
buggy()
function is expected to run each time with a fresh empty result list, add the arg argument to it, and then print a single-item list.def buggy(arg, result=[]): result.append(arg) print(result)buggy('a')buggy('b') # expect ['b']
def works(arg): result = [] result.append(arg) return resultworks('a')works('b')
def nonbuggy(arg, result=None): if result is None: result = [] result.append(arg) print(result)nonbuggy('a')nonbuggy('b')
Explode/Gather Positional Arguments with *
*
) is used inside the function with a parameter, it groups a variable number of positional arguments into a single tuple of parameter values. def print_args(*args): print('Positional tuple:', args)print_args()print_args(3, 2, 1, 'wait!', 'uh...')
*args
goes at the end and grabs all the rest:def print_more(required1, required2, *args): print('Need this one:', required1) print('Need this one too:', required2) print('All the rest:', args)print_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax')
We can pass positional argument to a function, which will match them inside to positional parameters.
We can pass a tuple argument to a function, and inside it will be a tuple parameter.
We can pass positional arguments to a function, and gather them inside as the parameter *args
, which resolves to the tuple args.
args
to positional parameters *args
inside the function, which will be regathered inside into the tuple parameter args
:def print_args(*args): print('Positional tuple:', args)print_args(2, 5, 7, 'x')args = (2,5,7,'x')print_args(args)print_args(*args)
*
syntax in a function call or definition:args
Outside the function, *args
explodes the tuple args
into comma-separated positional parameters.
Inside the function, *args
gathers all of the positional arguments into a single args tuple.
Explode/Gather Positional Arguments with **
**
) to group keyword arguments into a dictionary, where the argument names are the keys, and their values are the corresponding dictionary values.def print_kwargs(**kwargs): print('Keyword arguments:', kwargs)print_kwargs()print_kwargs(wine='merlot', entree='mutton', dessert='macaroon')
kwargs
is a dictionary parameter.We can pass keyword arguments to a function, which will match them inside to keyword parameters.
We can pass a dictionary argument to a function, and inside it will be dictionary parameters.
We can pass one or more keyword arguments (name=value) to a function, and gather them inside as **kwargs
, which resolves to the dictionary parameter called kwargs
.
Outside a function, **kwargs
explodes a dictionary kwargs
into name=value arguments.
Inside a function, **kwargs
gathers name=value arguments into the single dictionary parameter kwargs
.
Keyword-Only Arguments
def print_data(data, *, start=0, end=100): for value in (data[start:end]): print(value)
*
in the definition above means that the parameters start
and end
must be provided as named arguments if we don’t want their default values.data = ['a', 'b', 'c', 'd', 'e', 'f']print_data(data)print_data(data, start=4)print_data(data, end=2)
def print_data2(data, *, start, end): for value in (data[start:end]): print(value)print_data2(data)print_data2(data, start=4)print_data2(data, end=2)print_data2(data, start = 2, end = 4)
start
and end
are required arguments, because they doesn't have a default value and they must be specified as a keyword argument when we call the print_data2()
function.Mutable and Immutable Arguments
Remember that if you assigned the same list to two variables, you could change it by using either one? And that you could not if the variables both referred to something like an integer or a string?
If an argument is mutable, its value can be changed from inside the function via its corresponding parameter.
outside = ['one', 'fine', 'day']def mangle(arg): arg[1] = 'terrible!'outsidemangle(outside)outside
Keyboard shortcuts
↑, ←, Pg Up, k | Go to previous slide |
↓, →, Pg Dn, Space, j | Go to next slide |
Home | Go to first slide |
End | Go to last slide |
Number + Return | Go to specific slide |
b / m / f | Toggle blackout / mirrored / fullscreen mode |
c | Clone slideshow |
p | Toggle presenter mode |
t | Restart the presentation timer |
?, h | Toggle this help |
o | Tile View: Overview of Slides |
Esc | Back to slideshow |
A dictionary is similar to a list, but the order of items doesn't matter, and they aren't selected by an offset such as 0 or 1.
Instead, we specify a unique key to associate with each value.
This key is often a string, but it can actually be any of Python's immutable types: boolean, integer, float, tuple, string, and others.
Dictionaries are mutable, so we can add, delete, and change their key-value elements.
Create with {}
{}
) around comma-separated key : value pairs.empty_dict = {}empty_dict
Let's make a small dictionary with quotes from Ambrose Bierce's The Devil's Dictionary:
bierce = {"day": "A period of twenty-four hours, mostly misspent", "positive": "Mistaken at the top of one's voice", "misfortune": "The kind of fortune that never misses"}bierce
Create with dict()
dict()
function.acme_customer = {'first': 'Wile', 'middle': 'E', 'last': 'Coyote'}acme_customeracme_customer = dict(first = "Wile", middle = "E", last = "Coyote")acme_customer
dict()
need to be legal variable names (no spaces, no reserved words):x = dict(name="Elmer", def="hunter")
Convert with dict()
dict()
to convert two-value sequences into a dictionary.lol = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ]dict(lol)
lot = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]dict(lot)
tol = ( ['a', 'b'], ['c', 'd'], ['e', 'f'] )dict(tol)
los = [ 'ab', 'cd', 'ef' ]dict(los)
tos = ( 'ab', 'cd', 'ef' )dict(tos)
Add or Change an Item by [ key ]
Adding an item to a dictionary is not complicated.
Just refer to the item by its key and assign a value.
If the key was already present in the dictionary, the existing value is replaced by the new one.
If the key is new, it's added to the dictionary with its value.
Add or Change an Item by [ key ]
st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver' }st_city
st_city['NY'] = 'Rocjester'st_city
st_city['NY'] = 'Rochester'st_city
city_st = { 'Rochester': 'MN', 'Laramie': 'WY', 'Denver': 'CO', 'Rochester': 'NY' }city_st
Get an Item by [key]
or with get()
city_st = { 'Rochester': 'MN', 'Laramie': 'WY', 'Denver': 'CO', 'Rochester': 'NY' }city_st['Denver']
city_st['Buffalo']
in
and get()
in
:'Buffalo' in city_st
get()
function.city_st.get('Denver')
get()
function.city_st.get('Buffalo', 'Not in city_st')
get()
function.None
, which displays nothing in the console.city_st.get('Buffalo')
Get All Keys with keys()
keys()
to get all of the keys in a dictionary. signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.keys()list( signals.keys() ) # to turn the result into a list object.
Get All Values with values()
values()
:signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.values()list( signals.values() ) # to turn the result into a list object.
Get All Key-Value Pairs with items()
items()
function:signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.items()list( signals.items() ) # to turn the result into a list object.
Get Length with len()
signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}len(signals)
Combine Dictionaries with {**a, **b}
**
:first = {'a': 'agony', 'b': 'bliss'}second = {'b': 'bagels', 'c': 'candy'}{**first, **second}third = {'d': 'donuts'}{**first, **third, **second}
Combine Dictionaries with update()
update()
function to copy the keys and values of one dictionary into another.st_city
with other_city
st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }other_city = {'MA': 'Boston'}st_city.update(other_city)
Combine Dictionaries with update()
first = {'a': 1, 'b': 2}second = {'b': 'platypus'}first.update(second)first
Delete an Item by Key with del
del
:del st_city['NY']st_city
Get an Item by Key and Delete It with pop()
pop()
combines get()
and del
. pop()
a key and it exists in the dictionary, it returns the matching value and deletes the key-value pair. pop()
a second default argument, all is well and the dictionary is not changed:len(st_city)st_city.pop('MN') # Check len(st_city)st_city.pop('MN') # If it doesn't exist, it raises an exception:st_city.pop('MN', 'Not exist')
Delete All Items with clear()
clear()
or just reassign an empty dictionary ({}
) to the name:st_city.clear()st_cityst_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }st_city = {}st_city
Test for a Key with in
in
:st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }'NY' in st_city'WY' in st_city'CA' in st_city
Assign with =
signals = { 'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera' }save_signals = signalssignals['blue'] = 'confuse everyone'signals
save_signals
now? Copy with copy()
copy()
:signals = { 'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera' }original_signals = signals.copy()signals['blue'] = 'confuse everyone'signals
original_signals
now? Copy Everything with deepcopy()
signals
was a list instead of a single string:signals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_copy = signals.copy()signals
signals_copy
? Copy Everything with deepcopy()
signals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_copy = signals.copy()signals['red'][1] = 'sweat'signals
signals_copy
? Copy Everything with deepcopy()
deepcopy()
:import copysignals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_deepcopy = copy.deepcopy(signals)signalssignals_deepcopysignals['red'][1] = 'sweat'signals
signals_deepcopy
?Compare Dictionaries
==
and !=
:a = {1:1, 2:2, 3:3}b = {3:3, 1:1, 2:2}a == ba != ba <= b # does it work?
Iterate with for
and in
keys()
function) returns the keys. accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for card in accusation: # or, for card in accusation.keys(): print(card)
Iterate with for
and in
values()
function:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for value in accusation.values(): print(value)
Iterate with for
and in
items()
function:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for item in accusation.items(): print(item)
Iterate with for
and in
items()
, let's assign the first value (the key) to card, and the second (the value) to contents:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for card, contents in accusation.items(): print('Card', card, 'has the contents', contents)
Dictionary Comprehensions
Dictionary Comprehensions
word = 'letters'letter_counts = {letter: word.count(letter) for letter in word}letter_counts
Dictionary Comprehensions
word = 'letters'letter_counts = {letter: word.count(letter) for letter in set(word)}letter_counts
Dictionary Comprehensions
vowels = 'aeiou'word = 'onomatopoeia'vowel_counts = {letter: word.count(letter) for letter in set(word) if letter in vowels}vowel_counts
A set is like a dictionary with its values thrown away, leaving only the keys.
We use a set when we only want to know that something exists, and nothing else about it.
Common things to do with sets
Create with set()
set()
function or enclose one or more comma-separated values in curly brackets:empty_set = set()empty_seteven_numbers = {0, 2, 4, 6, 8}even_numbersodd_numbers = {1, 3, 5, 7, 9}odd_numbers
Convert with set()
set( 'letters' ) set( ['Dasher', 'Dancer', 'Prancer', 'Mason-Dixon'] )set( ('Ummagumma', 'Echoes', 'Atom Heart Mother') )set( {'apple': 'red', 'orange': 'orange', 'cherry': 'red'} )
Get Length with len()
reindeer = set( ['Dasher', 'Dancer', 'Prancer', 'Mason-Dixon'] )len(reindeer)
Add an Item with add()
add()
methods = set((1,2,3))ss.add(4)s
Delete an Item with remove()
s = set((1,2,3))s.remove(3)s
Iterate with for
and in
furniture = set(('sofa', 'ottoman', 'table'))for piece in furniture: print(piece)
Test for a Value with in
drinks
. drinks = { 'martini': {'vodka', 'vermouth'}, 'black russian': {'vodka', 'kahlua'}, 'white russian': {'cream', 'kahlua', 'vodka'}, 'manhattan': {'rye', 'vermouth', 'bitters'}, 'screwdriver': {'orange juice', 'vodka'} }
for name, contents in drinks.items(): if 'vodka' in contents: print(name)
cream
nor vermouth
but do vodka
:for name, contents in drinks.items(): if 'vodka' in contents \ and not ('vermouth' in contents or 'cream' in contents): print(name)
Combinations and Operators
drinks = { 'martini': {'vodka', 'vermouth'}, 'black russian': {'vodka', 'kahlua'}, 'white russian': {'cream', 'kahlua', 'vodka'} }bruss = drinks['black russian']wruss = drinks['white russian']a = {1, 2}b = {2, 3}
&
. intersection()
function does the same.a & ba.intersection(b)bruss & wruss
|
or the set union()
function:a | ba.union(b)bruss | wruss
-
or the difference()
function:a - ba.difference(b)bruss - wrusswruss - bruss
^
or symmetric_difference()
:a ^ ba.symmetric_difference(b)bruss ^ wruss
<=
or issubset()
:a <= ba.issubset(b)bruss <= wrussa <= a # any set is a subset of itself?a.issubset(a)
<
:a < bb < abruss < wruss
>=
or issuperset()
:a >= ba.issuperset(b)wruss >= brussa >= a # any set is a superset of itself?a.issuperset(a)
>
:a > bwruss > brussa > a
&
):for name, contents in drinks.items(): if contents & {'vermouth', 'orange juice'}: print(name)
for name, contents in drinks.items(): if 'vodka' in contents and not contents & {'vermouth', 'cream'}: print(name)
Set Comprehensions
a_set = {number for number in range(1,6) if number % 3 == 1}
Create an Immutable Set with frozenset()
frozenset()
function with any iterable argument:frozenset([3, 2, 1])frozenset(set([2, 1, 3]))frozenset({3, 1, 2})frozenset( (2, 3, 1) )fs = frozenset([3, 2, 1])fsfs.add(4)
[]
)()
){}
)marx_list = ['Groucho', 'Chico', 'Harpo']marx_tuple = ('Groucho', 'Chico', 'Harpo')marx_dict = {'Groucho': 'banjo', 'Chico': 'piano', 'Harpo': 'harp'}marx_set = {'Groucho', 'Chico', 'Harpo'}
marx_list[2]marx_tuple[2]marx_dict['Harpo']'Harpo' in marx_set
We can combine these built-in data structures into bigger, more complex structures of our own.
Let's start with three different lists:
newyork = ['Geneseo', 'Rochester', 'Buffalo']california = ['San Francisco', 'Los Angeles', 'San Diego']texas = ['Dallas', 'Houston', 'Austin']
tuple_of_lists = newyork, california, texastuple_of_lists
list_of_lists = [newyork, california, texas]list_of_lists
dict_of_lists = {'NY': newyork, 'CA': california, 'TX': texas}dict_of_lists
Class Exercises
1. Make an English-to-French dictionary called e2f
and print it. Here are your starter words: dog
is chien
, cat
is chat
, and walrus
is morse
.
2. Using your three-word dictionary e2f
, print the French word for walrus
.
3. Make a French-to-English dictionary called f2e
from e2f
Use the items
method.
4. Print the English equivalent of the French word chien
.
5. Print the set of English words from e2f
.
Class Exercises
6. Make a multilevel dictionary called life
. Use these strings for the topmost keys: 'animals
', 'plants
', and 'other
'. Make the 'animals' key refer to another dictionary with the keys 'cats
', 'octopi
', and 'emus
'. Make the 'cats
' key refer to a list of strings with the values 'Henri
', 'Grumpy
', and 'Lucy
'. Make all the other keys refer to empty dictionaries.
7. Print the top-level keys of life
.
8. Print the keys for life['animals']
.
9. Print the values for life['animals']['cats']
.
Class Exercises
10. Use a dictionary comprehension to create the dictionary squares
. Use range(10)
to return the keys, and use the square of each key as its value.
11. Use a set comprehension to create the set odd
from the odd numbers in range(10)
.
Define a Function with def
To define a Python function, we type def
, the function name, parentheses enclosing any input parameters to the function, and then finally, a colon (:).
Function names have the same rules as variable names (they must start with a letter or and contain only letters, numbers, or ).
def do_nothing(): pass # indention is needed here
pass
statement when we want Python to do nothing.do_nothing()
function just by typing its name and parentheses. do_nothing()
Call a Function with Parentheses
def make_a_sound(): print('quack') make_a_sound()
def agree(): return True
agree()
function and test its returned value by using if
:if agree(): print('Splendid!')else: print('That was unexpected.')
Arguments and Parameters
echo()
with one parameter called anything
.return
statement to send the value of anything back to its caller twice, with a space between:def echo(anything): return anything + ' ' + anythingecho('Geneseo')
The values we pass into the function when we call it are known as arguments.
When we call a function with arguments, the values of those arguments are copied to their corresponding parameters inside the function.
Arguments and Parameters
def echo(anything): return anything + ' ' + anythingecho('Geneseo')
The function echo()
was called with the argument string 'Geneseo'
.
'Geneseo'
was copied within echo()
to the parameter anything
, and then returned (in this case doubled, with a space) to the caller.Arguments and Parameters
commentary
, have it take an input string parameter
called color
, and make it return the string description to its caller:def commentary(color): if color == 'red': return "It's a tomato." elif color == "green": return "It's a green pepper." elif color == 'bee purple': return "I don't know what it is, but only bees can see it." else: return "I've never heard of the color " + color + "."
Arguments and Parameters
commentary()
with the string argument 'blue'
.comment = commentary('blue')
'blue'
to the function's internal color parameterif-elif-else
logic chaincomment
.print(comment)
A function can take any number of input arguments (including zero) of any type.
It can return any number of output results (also including zero) of any type.
return
explicitly, the caller gets the result None
.def do_nothing(): passprint(do_nothing())
None
Is Useful
None
is a special Python value that holds a place when there is nothing to say.
False
, although it looks false when evaluated as a boolean. thing = Noneif thing: print("It's some thing")else: print("It's no thing")
None
from a boolean False
value, use Python's is
operator:thing = Noneif thing is None: print("It's some thing")else: print("It's no thing")
None
to distinguish a missing value from an empty value.''
), lists ([]
), tuples ((,)
), dictionaries ({}
), and sets (set()
) are all False
, but are not the same as None
.None
, True
, or False
:def whatis(thing): if thing is None: print(thing, "is None") elif thing: print(thing, "is True") else: print(thing, "is False")
whatis(None)whatis(True)whatis(False)
whatis(0)whatis(0.0)whatis('')whatis("")whatis('''''')whatis(())whatis([])whatis({})whatis(set())
whatis(0.00001)whatis([0])whatis([''])whatis(' ')
Positional Arguments
The most familiar types of arguments are positional arguments, whose values are copied to their corresponding parameters in order.
This function builds a dictionary from its positional input arguments and returns it:
def menu(wine, entree, dessert): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('chardonnay', 'chicken', 'cake')
Positional Arguments
menu('beef', 'bagel', 'bordeaux')
Keyword Arguments
menu(entree='beef', dessert='bagel', wine='bordeaux')# Specify the wine first, but use keyword arguments for the entree and dessert:menu('frontenac', dessert='flan', entree='fish')
Specify Default Parameter Values
menu()
without the dessert
argument:def menu(wine, entree, dessert='pudding'): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('chardonnay', 'chicken')
def menu(wine, entree, dessert='pudding'): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('dunkelfelder', 'duck', 'doughnut')
Specify Default Parameter Values
buggy()
function is expected to run each time with a fresh empty result list, add the arg argument to it, and then print a single-item list.def buggy(arg, result=[]): result.append(arg) print(result)buggy('a')buggy('b') # expect ['b']
def works(arg): result = [] result.append(arg) return resultworks('a')works('b')
def nonbuggy(arg, result=None): if result is None: result = [] result.append(arg) print(result)nonbuggy('a')nonbuggy('b')
Explode/Gather Positional Arguments with *
*
) is used inside the function with a parameter, it groups a variable number of positional arguments into a single tuple of parameter values. def print_args(*args): print('Positional tuple:', args)print_args()print_args(3, 2, 1, 'wait!', 'uh...')
*args
goes at the end and grabs all the rest:def print_more(required1, required2, *args): print('Need this one:', required1) print('Need this one too:', required2) print('All the rest:', args)print_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax')
We can pass positional argument to a function, which will match them inside to positional parameters.
We can pass a tuple argument to a function, and inside it will be a tuple parameter.
We can pass positional arguments to a function, and gather them inside as the parameter *args
, which resolves to the tuple args.
args
to positional parameters *args
inside the function, which will be regathered inside into the tuple parameter args
:def print_args(*args): print('Positional tuple:', args)print_args(2, 5, 7, 'x')args = (2,5,7,'x')print_args(args)print_args(*args)
*
syntax in a function call or definition:args
Outside the function, *args
explodes the tuple args
into comma-separated positional parameters.
Inside the function, *args
gathers all of the positional arguments into a single args tuple.
Explode/Gather Positional Arguments with **
**
) to group keyword arguments into a dictionary, where the argument names are the keys, and their values are the corresponding dictionary values.def print_kwargs(**kwargs): print('Keyword arguments:', kwargs)print_kwargs()print_kwargs(wine='merlot', entree='mutton', dessert='macaroon')
kwargs
is a dictionary parameter.We can pass keyword arguments to a function, which will match them inside to keyword parameters.
We can pass a dictionary argument to a function, and inside it will be dictionary parameters.
We can pass one or more keyword arguments (name=value) to a function, and gather them inside as **kwargs
, which resolves to the dictionary parameter called kwargs
.
Outside a function, **kwargs
explodes a dictionary kwargs
into name=value arguments.
Inside a function, **kwargs
gathers name=value arguments into the single dictionary parameter kwargs
.
Keyword-Only Arguments
def print_data(data, *, start=0, end=100): for value in (data[start:end]): print(value)
*
in the definition above means that the parameters start
and end
must be provided as named arguments if we don’t want their default values.data = ['a', 'b', 'c', 'd', 'e', 'f']print_data(data)print_data(data, start=4)print_data(data, end=2)
def print_data2(data, *, start, end): for value in (data[start:end]): print(value)print_data2(data)print_data2(data, start=4)print_data2(data, end=2)print_data2(data, start = 2, end = 4)
start
and end
are required arguments, because they doesn't have a default value and they must be specified as a keyword argument when we call the print_data2()
function.Mutable and Immutable Arguments
Remember that if you assigned the same list to two variables, you could change it by using either one? And that you could not if the variables both referred to something like an integer or a string?
If an argument is mutable, its value can be changed from inside the function via its corresponding parameter.
outside = ['one', 'fine', 'day']def mangle(arg): arg[1] = 'terrible!'outsidemangle(outside)outside