Skip to content
Snippets Groups Projects
Commit 64cb2ae9 authored by Andy Kuemmel's avatar Andy Kuemmel
Browse files

Upload New File

parent d7d3a58c
No related branches found
No related tags found
No related merge requests found
%% Cell type:code id: tags:
``` python
# Warmup 1: Sort this dictionary by keys
# source: https://en.wikipedia.org/wiki/Big_Ten_Conference#Members (2021)
enrollments = { "Wisconsin": 45540, "Michigan": 47907, "Illinois": 52331,
"Iowa": 30448, "Minnesota": 52017, "Ohio State": 61369, "Northwestern": 22316}
# your answer here:
dict(sorted(enrollments.items()))
```
%% Output
{'Illinois': 52331,
'Iowa': 30448,
'Michigan': 47907,
'Minnesota': 52017,
'Northwestern': 22316,
'Ohio State': 61369,
'Wisconsin': 45540}
%% Cell type:code id: tags:
``` python
# wrong way?
sorted(enrollments.items())
```
%% Output
[('Illinois', 52331),
('Iowa', 30448),
('Michigan', 47907),
('Minnesota', 52017),
('Northwestern', 22316),
('Ohio State', 61369),
('Wisconsin', 45540)]
%% Cell type:code id: tags:
``` python
# Warmup 2: Sort enrollments by values ....use `extract`
print(enrollments)
def extract(s):
return s[-1]
dict(sorted(enrollments.items(), key=extract))
```
%% Output
{'Wisconsin': 45540, 'Michigan': 47907, 'Illinois': 52331, 'Iowa': 30448, 'Minnesota': 52017, 'Ohio State': 61369, 'Northwestern': 22316}
{'Northwestern': 22316,
'Iowa': 30448,
'Wisconsin': 45540,
'Michigan': 47907,
'Minnesota': 52017,
'Illinois': 52331,
'Ohio State': 61369}
%% Cell type:code id: tags:
``` python
# alternate way to do the same thing with lambdas:
dict(sorted(enrollments.items(), key = lambda t : t[-1]))
```
%% Output
{'Northwestern': 22316,
'Iowa': 30448,
'Wisconsin': 45540,
'Michigan': 47907,
'Minnesota': 52017,
'Illinois': 52331,
'Ohio State': 61369}
%% Cell type:code id: tags:
``` python
# Warmup 3: Sort this list of dictionaries by 'name'
volunteers = [ {"name": "Skylar", "hours": 53},
{"name":"Patrice", "hours": 72},
{"name":"Gabriella", "hours": 45},
{"name": "Jayden", "hours": 62} ]
def extract_name(d):
return d['name']
sorted(volunteers, key=extract_name)
```
%% Output
[{'name': 'Gabriella', 'hours': 45},
{'name': 'Jayden', 'hours': 62},
{'name': 'Patrice', 'hours': 72},
{'name': 'Skylar', 'hours': 53}]
%% Cell type:code id: tags:
``` python
# alternate way with lambda:
sorted(volunteers, key= lambda d:d['name'])
```
%% Output
[{'name': 'Gabriella', 'hours': 45},
{'name': 'Jayden', 'hours': 62},
{'name': 'Patrice', 'hours': 72},
{'name': 'Skylar', 'hours': 53}]
%% Cell type:code id: tags:
``` python
# What is a lambda function?
# an abstraction (shortcut) for a function
# remove the def, name, and return statement
# just describe the parameter and the return value
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# Warmup 4: Sort the above list of dictionaries by 'hours'
sorted(volunteers, key= lambda d:d['hours'], reverse=True)
```
%% Output
[{'name': 'Patrice', 'hours': 72},
{'name': 'Jayden', 'hours': 62},
{'name': 'Skylar', 'hours': 53},
{'name': 'Gabriella', 'hours': 45}]
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# Warmup 5: Sort this lists of strings by length of string
fruits = ["apple", "blueberry", "cherry", "date", "fig", "grapefruit"]
sorted(fruits, key = len)
```
%% Output
['fig', 'date', 'apple', 'cherry', 'blueberry', 'grapefruit']
%% Cell type:code id: tags:
``` python
# Warmup 6: Sort this dictionary of lists by length of list
cities_by_county = {"Dane": ["Madison", "Sun Prairie", "Middleton", "Waunakee"],
"Rock": ["Janesville", "Beloit"],
"Milwaukee": ["Milwaukee", "West Allis", "Wauwatosa"],
"Waukesha": ["Brookfield"]}
dict(sorted(cities_by_county.items(), key = lambda t: len(t[-1])))
```
%% Output
{'Waukesha': ['Brookfield'],
'Rock': ['Janesville', 'Beloit'],
'Milwaukee': ['Milwaukee', 'West Allis', 'Wauwatosa'],
'Dane': ['Madison', 'Sun Prairie', 'Middleton', 'Waunakee']}
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
## Lecture 24: Comprehensions
Learning Objectives:
- Create list and dictionary comprehensions
%% Cell type:markdown id: tags:
### 25.1 Create list and dictionary comprehensions
Python frequently gives us ways to shorten code
A comprehension is a shortcut to using a for loop
%% Cell type:code id: tags:
``` python
# Given this list what kind of filtered list could we make from it?
# By filtered, think about keeping certain words
fruits = ["apple", "blueberry", "cherry", "DATE", "FIG", "grapefruit"]
# Talk to your partner and come up with different ideas
# just words that all uppercase
# just the lengths of each word
# keep the short words
```
%% Cell type:code id: tags:
``` python
# long way: using a for loop
new_list = []
for w in fruits:
if len(w) > 5:
new_list.append(w)
new_list
```
%% Output
['blueberry', 'cherry', 'grapefruit']
%% Cell type:code id: tags:
``` python
# Do the same thing using a comprehension
# Tip: Write them in reverse, naming the variable last
[ w for w in fruits if len(w) > 5]
```
%% Output
['blueberry', 'cherry', 'grapefruit']
%% Cell type:code id: tags:
``` python
# list of words in fruits that are all uppercase
fruits = ["apple", "blueberry", "cherry", "DATE", "FIG", "grapefruit"]
upper_words = [ w for w in fruits if w == w.upper() ]
upper_words
```
%% Output
['DATE', 'FIG']
%% Cell type:code id: tags:
``` python
# list of just the lengths of each word
[ len(w) for w in fruits ]
```
%% Output
[5, 9, 6, 4, 3, 10]
%% Cell type:code id: tags:
``` python
# list of all the short words, length < 6 but make them uppercase
[ w.upper() for w in fruits if len(w) < 6]
```
%% Output
['APPLE', 'DATE', 'FIG']
%% Cell type:code id: tags:
``` python
# list of words that contain the letter "A" or "a"
[ w for w in fruits if "A" in w.upper()]
```
%% Output
['apple', 'DATE', 'grapefruit']
%% Cell type:code id: tags:
``` python
# Given this list of dictionaries, what kind of lists could we make from it?
# Talk to your partner and come up with different ideas
volunteers = [ {"name": "Skylar", "hours": 53},
{"name":"Patrice", "hours": 72},
{"name":"Gabriella", "hours": 45},
{"name": "Jayden", "hours": 62}
]
```
%% Cell type:code id: tags:
``` python
[ d['name'] for d in volunteers]
```
%% Output
['Skylar', 'Patrice', 'Gabriella', 'Jayden']
%% Cell type:code id: tags:
``` python
[ d['hours'] for d in volunteers if "e" in d['name'] ]
```
%% Output
[72, 45, 62]
%% Cell type:code id: tags:
``` python
[ (d['name'], d['hours'] ) for d in volunteers ]
```
%% Output
[('Skylar', 53), ('Patrice', 72), ('Gabriella', 45), ('Jayden', 62)]
%% Cell type:code id: tags:
``` python
# Given this dictionary, what list could we make?
cities_by_county = {"Dane": ["Madison", "Sun Prairie", "Middleton", "Waunakee"],
"Milwaukee": ["Milwaukee", "West Allis", "Wauwatosa"],
"Rock": ["Janesville", "Beloit"],
"Waukesha": ["Brookfield"]}
```
%% Cell type:markdown id: tags:
### The syntax of Comprehensions
%% Cell type:markdown id: tags:
![comprehensions.png](attachment:comprehensions.png)
%% Cell type:markdown id: tags:
### if/else in a comprehension has a different ordering
%% Cell type:code id: tags:
``` python
# If/else...
# convert these Fahrenheit temps to an int in Celsius using C = 5/9 * (F-32)
temps = ["32", "45", "90", "212"]
[5/9 * (int(f)-32) for f in temps]
```
%% Output
[0.0, 7.222222222222222, 32.22222222222222, 100.0]
%% Cell type:code id: tags:
``` python
# do it again, but change empty strings to None
# need to use an if else clause which must come before the 'for'
# new_list = [expression if conditional_expression else alternate_expression for val in iterable ]
temps = ["32", "45", "90", "", "212"]
[5/9 * (int(f)-32) if f != "" else None for f in temps ]
```
%% Output
[0.0, 7.222222222222222, 32.22222222222222, None, 100.0]
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
### Dictionary Comprehensions
We use a for loop that iterates over dict.items()
We use the concept of 'tuple unpacking' by writing a `for (k,v) in dictname.items()`
%% Cell type:code id: tags:
``` python
scores_dict = {"Bob": [18, 72, 83],
"Cindy" : [27, 11, 55, 73, 87],
"Alice": [16, 33, 42, 89, 90],
"Meena": [39, 93, 9, 3, 55, 72, 19]}
# Create a dictionary where the key is the same, but the value is the max score in each list
{ k : max(v) for (k,v) in scores_dict.items() }
```
%% Output
{'Bob': 83, 'Cindy': 87, 'Alice': 90, 'Meena': 93}
%% Cell type:code id: tags:
``` python
# Create a dictionary where the key is the same, but the value is the average score
{ k : sum(v)/len(v) for (k,v) in scores_dict.items() }
```
%% Cell type:code id: tags:
``` python
# Create a single dictionary where the key is the name and the value is the hours.
volunteers = [ {"name": "Skylar", "hours": 53},
{"name":"Patrice", "hours": 72},
{"name":"Gabriella", "hours": 45},
{"name": "Jayden", "hours": 62} ]
{ d['name'] : d['hours'] for d in volunteers}
```
%% Output
{'Skylar': 53, 'Patrice': 72, 'Gabriella': 45, 'Jayden': 62}
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# For more reference
# https://www.w3schools.com/python/python_lists_comprehension.asp
# https://www.datacamp.com/community/tutorials/python-dictionary-comprehension
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment