Skip to content

Instantly share code, notes, and snippets.

@imomaliev
Last active July 9, 2019 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imomaliev/d5b918116f0323d07626b97c25f6d2e3 to your computer and use it in GitHub Desktop.
Save imomaliev/d5b918116f0323d07626b97c25f6d2e3 to your computer and use it in GitHub Desktop.
"""
Calculate second lowest cost silver plan (SLCSP) and produce result.csv.
"""
import csv
from collections import defaultdict
def get_slcsp_zipcodes():
"""Get all zipcodes for slcsp research."""
with open("slcsp.csv", "r") as csvfile:
slcsp = csv.reader(csvfile)
# skip headers
next(slcsp)
return [row[0] for row in slcsp]
def map_plans():
"""Create mapping for all 'Silver' rates in rate_area."""
plans_mapping = defaultdict(set)
with open("plans.csv") as csvfile:
plans = csv.DictReader(csvfile)
for row in plans:
if row["metal_level"] == "Silver":
rate_area = (row["state"], row["rate_area"])
plans_mapping[rate_area].add(float(row["rate"]))
return plans_mapping
def map_zips(slcsp_zips, plans_mapping):
"""Create mapping of zipcodes with all rates."""
zips_mapping = {}
with open("zips.csv") as csvfile:
zips = csv.DictReader(csvfile)
for row in zips:
zipcode = row["zipcode"]
if zipcode in slcsp_zips:
if zipcode not in zips_mapping:
rate_area = (row["state"], row["rate_area"])
zips_mapping[zipcode] = plans_mapping[rate_area]
else:
# zip should be in only one area
zips_mapping[zipcode] = None
return zips_mapping
def process_zips_mapping(zips_mapping):
"""Create mapping of zipcodes for our research that have slcsp."""
processed_mapping = {}
for zipcode, rates in zips_mapping.items():
if rates is None:
continue
sorted_rates = sorted(rates)
if len(sorted_rates) < 2:
continue
processed_mapping[zipcode] = "{0:.2f}".format(sorted_rates[1])
return processed_mapping
def main():
slcsp_zips = get_slcsp_zipcodes()
plans_mapping = map_plans()
zips_mapping = map_zips(slcsp_zips, plans_mapping)
processed_mapping = process_zips_mapping(zips_mapping)
with open("result.csv", "w") as csvfile:
slcsp = csv.writer(csvfile)
slcsp.writerow(("zipcode", "rate"))
for zipcode in slcsp_zips:
slcsp.writerow((zipcode, processed_mapping.get(zipcode, "")))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment