Now You Code In Class : US Senators

Write a program to load the JSON data file 'NYC0-US-Senators-2019.json' *** and perform a data analysis over the file. It should load the file as a list of dictionary and then allow the user to perform the following functions:

  1. List a count of senators by party affiliation
  2. List a count senators gender.

Consider writing 1. and 2. as functions which take the list of senators as input and output a dictionary of the party and gender counts respectively.

HINT: Build dictionary of the values and and count them. That way you don't have to know the the parties or genders in advance. Basically this works like the word count example from the severance reading and is a common approach used in computing to aggegrate values.

Sample run:

Analysis of US Senators: 
Party Counts {'republican': 53, 'democrat': 45, 'independent': 2}
Gender Counts {'male': 75, 'female': 25}

*** This file was extracted from: https://www.govtrack.us/api/v2/role?current=true&role_type=senator

Step 1: Problem Analysis

This function should get input from the user at run time and return the input address.

Inputs:

Outputs:

Algorithm (Steps in Program):


In [15]:
# Write code 
def count_gender(senators):
    gender_dict = {}
    for senator in senators:
        gender = senator['person']['gender'].lower()
        gender_dict[gender] = gender_dict.get(gender,0) +1
        
    return gender_dict

def count_party(senators):
    party_dict =  {}
    for senator in senators:
        party = senator['party'].lower()
        party_dict[party] = party_dict.get(party,0) +1
        
    return party_dict

file = 'NYC0-US-Senators-2019.json'
with open(file, 'r') as f:
    senators = json.load(f)

gender = count_gender(senators)
party = count_party(senators)
    
print("Analysis of US Senators: ")
print(f"Party Counts {party}")
print(f"Gender Counts {gender}")


Analysis of US Senators: 
Party Counts {'republican': 53, 'democrat': 45, 'independent': 2}
Gender Counts {'male': 75, 'female': 25}

In [5]:
# code to update the senators in case you want fresh data!

import requests
import json 
senators = requests.get('https://www.govtrack.us/api/v2/role?current=true&role_type=senator').json()['objects']
with open('NYC0-US-Senators-2019.json','w') as f:
    f.write(json.dumps(senators))