World Cup DIctReader Solution

# Simulate a sports tournament

from csv import DictReader
from sys import argv, exit
import random

# Number of simluations to run
N = 1000

def main():

    # Ensure correct usage
    if len(argv) != 2:
        exit("Usage: python tournament.py FILENAME")

    teams = []
    # TODO: Read teams into memory from file
    with open(argv[1]) as csvfile:
        # access the fieldnames "keys" property of the dictreader obj
        keys = DictReader(csvfile).fieldnames

        # create a dictreader obj and cast to list of dictionaries
        teams = list(DictReader(csvfile))
        # cast ratings in each dictionary to integers
        for dct in teams:
            # calling on keys by fieldnames property of dictreader obj
            dct[keys[1]] = int(dct[keys[1]])

    print(type(teams[0]["rating"]))
    counts = {}
    # TODO: Simulate N tournaments and keep track of win counts

    # Print each team's chances of winning, according to simulation
    for team in sorted(counts, key=lambda team: counts[team], reverse=True):
        print(f"{team}: {counts[team] * 100 / N:.1f}% chance of winning")


def simulate_game(team1, team2):
    """Simulate a game. Return True if team1 wins, False otherwise."""
    rating1 = team1["rating"]
    rating2 = team2["rating"]
    probability = 1 / (1 + 10 ** ((rating2 - rating1) / 600))
    return random.random() < probability


def simulate_round(teams):
    """Simulate a round. Return a list of winning teams."""
    winners = []

    # Simulate games for all pairs of teams
    for i in range(0, len(teams), 2):
        if simulate_game(teams[i], teams[i + 1]):
            winners.append(teams[i])
        else:
            winners.append(teams[i + 1])

    return winners


def simulate_tournament(teams):
    """Simulate a tournament. Return name of winning team."""
    # TODO


if __name__ == "__main__":
    main()