Created
February 2, 2023 00:58
-
-
Save shaunagm/1c6b9ce1ae788a461251fec7bcea3168 to your computer and use it in GitHub Desktop.
snippets for Parsons "Intro to Python" training
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Here's some data to play with! | |
data = [ | |
{'first_name': 'Megan', 'last_name': 'Rapinoe', 'age': '37', 'date_updated': '1674121763'}, | |
{'first_name': 'Tobin', 'last_name': 'Heath', 'age': '34', 'date_updated': '1664121763'}, | |
{'first_name': 'Crystal', 'last_name': 'Dunn', 'age': '31', 'date_updated': '1664121763'}, | |
{'first_name': 'Midge', 'last_name': 'Purce', 'age': '26', 'date_updated': '1664121763'}, | |
{'first_name': 'Sophia', 'last_name': 'Smith', 'age': '23', 'date_updated': '1664121763'} | |
] | |
# This is a list of dictionaries, which are filled with strings. | |
# (Lists and dictionaries can hold different types of things, including other lists and dictionaries!) | |
# We can access them like this: | |
midge_age = data[4]["age"] # Note: zero-indexing, different ways to access list and dictionary | |
# what if you look for a key that's not there? | |
midge_vote = data[4]["voter_status"] # oh no an error! | |
midge_vote = data[4].get("voter_status") # returns None | |
midge_vote = data[4].get("voter_status", "unknown") # can set a default value | |
print(type(midge_age)) # check types (note: nesting print and type here) | |
new_variable = int(midge_age) # convert types | |
print(type(new_variable)) | |
# Python built-in types: integer, string, boolean, float, list, dict, object, None | |
# One common but more complex type is datetimes | |
import datetime # imports are a thing! | |
result = datetime.datetime.fromtimestamp(data[0]["date_updated"]) | |
print(type(result)) | |
for person in data: # iterating through a list gives the whole item | |
print(person) | |
for column_name in data[0]: # iterating through a dictionary just gives the key | |
print(column_name) | |
for column_value in data[0].values(): # get values instead | |
print(column_value) | |
for column_name, column_value in data[0].items(): # get both! | |
print(column_name, column_value) | |
# Fancy way to do this in Python: "comprehensions" | |
ages = [person["age"] for person in data] | |
data_dict = { person["last_name"]: [person["first_name"], person["age"]] for person in data } | |
# What if you want to select some things and not others? | |
for person in data: | |
if int(person["age"]) > 30: | |
print(f"{person['first_name'] person['last_name'] is over 30!}") # hey, f-strings! | |
else: | |
print(f"{person['first_name'] person['last_name'] is under 30!}") | |
# Add conditions with "elif": | |
for person in data: | |
if int(person["age"]) > 30: | |
print(f"{person['first_name'] person['last_name'] is over 30!}") # hey, f-strings! | |
elif int(person["age"]) > 25: | |
print(f"{person['first_name'] person['last_name'] is over 25 but under 30!}") | |
else: | |
print(f"{person['first_name'] person['last_name'] is under 30!}") | |
# Note: sometimes we "refactor" to remove redundant bits, like so: | |
for person in data: | |
age_string = "" | |
if int(person["age"]) > 30: | |
age_string = "over 30" | |
elif int(person["age"]) > 25: | |
age_string = "over 25 but under 30" | |
else: | |
age_string ="under 30" | |
print(f"{person['first_name'] person['last_name'] is {age_string}}!") | |
# See also: continue, break | |
# You can use if/else with comprehensions! | |
ages_over_30 = [person["age"] for person in data if int(person["age"]) > 30] | |
# Move things into functions | |
def create_age_string(person): | |
age_string = "" | |
if int(person["age"]) > 30: | |
age_string = "over 30" | |
elif int(person["age"]) > 25: | |
age_string = "over 25 but under 30" | |
else: | |
age_string ="under 30" | |
return f"{person['first_name'] person['last_name'] is {age_string}}!" | |
for person in data: | |
print(create_age_string(person)) | |
# Can set multiple inputs, default values, keyword arguments, etc | |
# Loading data from an external file like a csv. | |
# Version 1: With Python Standard Library | |
import csv | |
with open('data.csv') as csvfile: | |
reader = csv.DictReader(csvfile) | |
data = list(reader) | |
print(data) | |
# Version 2: With Parsons | |
from parsons import Table | |
import datetime | |
data = Table.from_csv(".data.csv") | |
print(data) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment