Dictionary Practice

Below is a series of problems divided into several categories. We expect students from CS111 to be able to complete all the core problems. We also have a series of problems dealing with election data. Dictionaries are often used in the context of real data so this is good practice. Finally, we have a series of challenge problems for those who complete the main tasks.

Core Problems

Accessing

Predict what the following results will be before executing the cell.

Challenge: The two below are tricky!

Mutating Dictionaries

Consider the dictionary below. Follow the mutations below and predict what the final outcome of the dictionary will be.

Below are some mutations for the dictionary dct.

Predict the outcome of the mutations before checking your answer below.

Predict what the dictionary will look like after running the line below.

Predict the outcome of the mutations before checking your answer below.

Who Won?

Below you will write two functions to determine whether a team beat another team in some competition. A team is represented by a dictionary where the keys are the names of the players and the values are the scores that each player contributes to the overall team score. Below is an example of a team dictionary.

{"Andy":10, "Sohie":12}

Write a function teamTotal that takes a team dictionary and reports the overall score of the team. For example, a call to teamTotal({"Andy":10, "Sohie":12}) returns a value of 22.

Write a function called whoWon that takes two team dictionaries and prints out which team won. If the result is a tie, the function should print out that a tie occurred.

Working With Data

Below is a piece of code to import some data about Senate elections from 1976-2018 and store those results in a dictionary called senateDct. senateDct is a dictionary with every Senate election excluding special runoff elections. Every key-value pair in senateDct contains the information for an election in a particular state during a particular year. The keys to the Senate dictionary are a tuple of year and state and the values are a dictionary containing the information for a particular year. For example, below is the information for the 1978 Senate election in Kansas. Note that this key-value pair is one of many in the larger dictionary senateDct.

(1978, 'Kansas'): {
    'names': ['Nancy Landon Kassebaum', 'James R. Maher', 'Russell Mikels', 'Bill Roy'], 
    'parties': ['republican', 'conservative', 'prohibition', 'democrat'], 
    'writein': [False, False, False, False], 
    'votes': [403354, 22497, 5386, 317602], 
    'totalvotes': 748839
}

The key 'names' lists all the candidates in that election. The key 'parties' lists all the parties of each candidate in the same order as the names. Therefore, in this example, Nancy Kassebaum is the Republican and Bill Roy is the Democrat. The key 'writeins' has a value listing whether the candidates were writeins (also preserving the same order). The key 'votes' also lists the votes of each candidate in the same order as the names. So Nancy Kassebaum won this election with 403,354 votes.

IMPORTANT: When working with the senateDct below, do not mutate or change the dictionary or any of its sub-values!

electionExists

Write a predicate called electionExists that determines whether an election was held in a particular state and year.

mostVotesCast

Write a function called mostVotesCast that iterates through the senateDct and determines which election as a tuple (year and state) had the most votes cast.

Hint: it's likely to be California but which year?

You can check your answer below by scrolling down to the end of the notebook.

Number of Different Political Parties

America has actually had quite a number of different political parties over the course of its history, most of them with relatively small numbers. Write a function listPoliticalParties that returns a list of all the parties represented in Senate elections from 1976-2018. Your list should contain unique entries. For example, 'republican' should only be included once.

If you look at the data below, you will notice that there are some strange political parties listed like 'none' and ''. These are likely write-in candidates and are not political parties. So our list won't be entirely accurate.

Election Winner

Write a function called electionWinner that takes a year and state and returns who won that election. If an election did not take place during that year/state, electionWinner should return the string 'Unknown'. If the election did take place, the winner should be returned as a tuple with the elements of name, party, and percent of vote won. Round the percent to the hundreds place.

You may find the method .index helpful when solving this problem. The .index method returns the index of some value in a sequence. Therefore, the .index method is a appropriate for any sequence.

If the value does not exist in the sequence, then a ValueError is raised.

Note you may not need to use the .index method when implementing your solution but it can be helpful depending upon your approach.

Curious about another state and year? Call electionWinner below!

thirdCandidates

Write a function called thirdCandidates that returns a list of tuples where each tuple represents an election not won by a Democrat or Republican. Note that in the Senate dictionary that a Republican is the string 'republican' and a Democrat is the string 'democrat'. You should use the function electionWinner from above. Note that the tuple for each election should state the year of the election, the state, the name of the candidate, their party, and the percent of the overall vote that they obtained.

See the answers at the bottom of the notebook to check if your implementation produced the correct list.

writeInWinners

Below write a function called writeInWinners that returns a list of tuples for all Senate candidates who won their seat as a write-in candidate. You should use the function electionWinner from above. Note that the tuple for each election should state the year of the election, the state, the name of the candidate, and the percent of the overall vote that they obtained.

See the answers at the bottom of the notebook to check if your implementation produced the correct list.

Challenge Problems

These problems are harder and more like problem set questions.

IMPORTANT: Do not modify or mutate the Senate dictionary when implementing your solution!

closeRaces

Elections can be quite tight in some years. Below write a function called closeRaces that iterates through the Senate dictionary to find all the close senate races over the years and store those results in a list of tuples. For every close race, the tuple should contain the year of the election, the state, and the margin of victory. closesRaces should take a threshold parameter which indicates the threshold for including an election as a close race. For example, if the threshold were equal to 4000, then the 1986 Senate election in North Dakota would be included because the highest vote getter (Democrat Kent Conrad) barely beat the second highest vote getter (incumbent Republican Mark Andrews) by only 2,120 votes.

Third-Party Split

After election results come out, there is often much discussion about how third-party candidates split the vote in tight elections. Write a function called thirdPartySplit that returns a list of elections where if all the votes excluding those for the top two candidates were instead given to the runner-up, that the election outcome would have been different. The list should contain tuples for each election where the tuple contains the year and state of the election.

How many elections could have been changed if the third party vote had gone to the second place finisher?

Other Questions

There are of course plenty of other questions we could ask about the data. Here are some other interesting questions to try and tackle:

What other questions could we ask? If you have time try and tackle some of these questions with your own functions below.

Answers

Question: What state and in what year were the most votes cast for a senate race?
Answer: California, 2012

Question: How many times have senators won their election race who were not registered as democrats and republicans? Answer: 13! Harry F. Byrd Jr., Paul Wellstone, Mark Dayton, Kent Conrad, Joe Lieberman, Amy Klobuchar (2), Bernie Sanders (3), Lisa Murkowski, Angus King (2).

Question: How many times have senators won their election race as a write-in candidate? Answer: 1! Lisa Murkowski