python - Using 'itemgetter' to sort on last, first name in a tuple from a dictionary? -
my programs reads input dictionary, formats have title formatting, , outputs read. assignment required don't use dictreader
. i'd sort on last name, , first name using itemgetter
. can see, have working version of code using lambda
function, i'd same result aforementioned itemgetter
function.
import sys operator import itemgetter, attrgetter, methodcaller def data_2_dict(line): # constants name = 0 addr = 1 addr2 = 2 city = 3 state = 4 zip = 5 # split line , populate dictionary line = line.rstrip('\n') element = line.split(',') data_dict = { 'name' : tuple(element[name].split(' ')), 'address' : element[addr], 'address2' : element[addr2], 'city' : element[city], 'state' : element[state], 'zip' : element[zip], } return format_data(data_dict) def format_data(dict): key, value in dict.iteritems(): if key != 'name' , key != 'state' , key != 'zip': dict[key] = value.title() elif key == 'name': dict[key] = (value[0].title(), value[1].title()) return dict def main(): # gather in , out file, open objects infile = sys.argv[1] outfile = sys.argv[2] cust_list = [] open(infile, 'r') myinfile: line in myinfile.read().splitlines(): data = data_2_dict(line) cust_list.append(data) # cust_list_sorted = sorted(cust_list, key=lambda key: (key['name'][1], key['name'][0])) cust_list_sorted = sorted(cust_list, key=itemgetter('name'[1], 'name'[0])) open(outfile, 'w') myoutfile: line in cust_list_sorted: nameline = 'name: {0}, {1} ---\n'.format(line['name'][1], line['name'][0]) myoutfile.write(nameline) addrline = '\taddress: {0}, {1} {2}\n'.format(line['address'],line['city'], line['state']) myoutfile.write(addrline)
a line of input looks this:
michelle fuller,265 madeira ave,,chillicothe,oh,00045
and line of output should this:
name: fuller, michelle --- address: 265 madeira ave, chillicothe oh
this not possible itemgetter
, returns callable fetches item operand, because want fetching item 0 item "name" operand.
if have use itemgetter
, can split , store "firstname" , "lastname" in dictionary , use itemgetter("lastname", "firstname")
.
Comments
Post a Comment