Skip to content

Instantly share code, notes, and snippets.

@Radcliffe
Created May 26, 2017 03:18
Show Gist options
  • Save Radcliffe/8fb354d6964dd5e1a10e0ccb4519fd94 to your computer and use it in GitHub Desktop.
Save Radcliffe/8fb354d6964dd5e1a10e0ccb4519fd94 to your computer and use it in GitHub Desktop.
# Filename: pick_state.py
# To run this file, type
# python pick_state.py
# in a terminal window.
# This script requires the file us_states.txt which is available at
# https://gist.github.com/Radcliffe/7a3e0fe2efc0a9aeb523abfac67865db
import csv
import random
# Read the file us_states.txt into a list of dictionaries.
with open('us_states.txt') as input_file:
states = list(csv.DictReader(input_file, delimiter='|'))
# For example:
# states[0]['StateName'] == 'Alaska'
# states[0]['StateCode'] == 'AK'
# states[0]['StateDate'] == '1819-12-14'
# states[1]['StateName'] == 'Alabama'
# etc.
# Pick a random state
state = random.choice(states)
# Display information about the state, using a template.
template = "{StateName} joined the Union on {StateDate}, and its postal code is {StateCode}."
print(template.format(**state))
# The ** operator expands a dictionary into keyword arguments.
# The last line is equivalent to the following (much more verbose) statement:
# print(template.format(StateName=state['StateName'],
# StateDate=state['StateDate'],
# StateCode=state['StateCode']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment