I want to list all names in a file that uses a dictionary by date of birth. I want the oldest to be the first and so on down to the youngest. Here is my code, what would I need to add for this:
#!/usr/bin/python
import sys
import operator
import re
from operator import itemgetter
from datetime import datetime
dictionary={}
f = open('names.txt', "r")
for line in f:
test = re.split(r'\s*[;,.]\s*', line)
name = test[0]
bDay = test[1]
removeNLine =len(bDay)-1 # get the D.0.B but remove the /n
bDay = bDay[0:removeNLine]
dictionary[name] = datetime.strptime(bDay,"%d/%m/%Y")
#for y,v in sorted(d.iteritems(), key=lambda (k,v1): (v1,k)):
#d2 = sorted(d.values())
#d2= sorted(d.keys(), key=d.get, reverse = False)
#d2= sorted(d.keys(), key=operator.itemgetter(1))
#print d2
#for y in d:
for name,birth in dictionary.items():
dob = dictionary[name]
timeFormat = dob # just edited
timeNow = datetime.now()
daysTime = timeNow -timeFormat
days = daysTime.days
age = days / 365
print name,age
So my file has a name and a birthday and I want to sort by the birthday from what I have been reading I probably should be able to do it with datetime.strptime but I cant understand how to sort with it. Any ideas on improving the code too will be appreciated but bare in mind that I am new to this and generally very poor at programming languages so readability and the ability to understand fairly easy would be helpful.
the file is as follows:
tom 12/12/1999
ted ; 01/04/2008
tim ; 01/02/2001
mike 09/03/1997
sorted(dictionary, key=dictionary.get)?