Skip to content

Instantly share code, notes, and snippets.

@christophergregory
Created August 27, 2014 14:24
Show Gist options
  • Save christophergregory/92e87b08d0aed68039ab to your computer and use it in GitHub Desktop.
Save christophergregory/92e87b08d0aed68039ab to your computer and use it in GitHub Desktop.
Python 101 Assignment 3 Solution 1
people = {} # let's start with an empty dictionary to hold our data
with open('numbers.txt', 'r') as numbers:
for index, line in enumerate(numbers):
if index > 0: # skip the first line (don't need the headers)
name, birthday = line.rstrip().split(',')
# study this line carefully, it's intentionally terse
people.update({ name : { 'number' : birthday } })
with open('birthdays.txt', 'r') as birthdays:
for line in birthdays:
name, birthday = line.rstrip().split(',')
try:
people[name]['birthday'] = birthday # Update each person in the dictionary with the birthday data
except KeyError, e: # skip any missing keys i.e. the header column
print "KeyError: Skip this line, {} not found".format(e)
with open('output.txt', 'w') as output:
# Write column headers
output.write('name,birthday,number\n')
# Write each line to the new output.txt file
for key, value in people.iteritems():
name, number, birthday = key, value['number'], value['birthday']
line = '{},{},{}\n'.format(name, number, birthday)
output.write(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment