python - Assign key & value for list? -
here program far:
file = open('cass.txt', 'r') f = file.readlines() file.close() classcode = input('please enter class code: ' ) print("class list for", classcode) line in f: if line.find(classcode)>=0: names = line.split() names1 = names[0].split(',')[0:3] print(names1)
and output class tda3m102 is
['abdull', 'sonia', 'f'] ['armstrong', 'sammi', 'f'] ['barrey', 'tina', 'f'] ['bu', 'kyle', 'm'] ['cheng', 'henry', 'm'] ['dance', 'daniel', 'm'] ['east', 'adam', 'm'] ['frasier', 'annie', 'f'] ['han', 'brandon', 'm'] ['huang', 'peter'] ['kauffman', 'fredricka', 'f'] ['lunsford', 'mike', 'm'] ['leung', 'dan', 'm'] ['li', 'annika', 'f'] ['li', 'ben', 'm'] ['muhummad', 'artom', 'm'] ['nguyen', 'tim', 'm'] ['peterson', 'elena'] ['shneider', 'samantha', 'f'] ['sun', 'yu', 'm'] ['vance', 'adam', 'm'] ['wen', 'william', 'm'] ['woods', 'larry', 'm'] ['yan', 'harry']
i have convert list dictionary , assign first name & last name each student key , gender value. if there no gender, program should set random gender.. i'm not sure how go this. ideas?
here's tried:
mydict = {} name in names1: if name in mydict: mydict[name] += 1 else: mydict[name] = 1 print(mydict)
and output was:
{'yan': 1, 'harry': 1}
for reason recognizes 1 name (last name in list) , outputs values that.
you somehting this:
names1 = [['abdull', 'sonia', 'f'], ['armstrong', 'sammi', 'f'], ['barrey', 'tina', 'f'], ['bu', 'kyle', 'm'], ['cheng', 'henry', 'm'], ['dance', 'daniel', 'm'], ['huang', 'peter']] import random mydict = {} lname,*rest in names1: fname = rest[0] gender = rest[1] if len(rest) == 2 else random.choice(['m','f']) key = fname + ' ' + lname if key not in mydict: mydict[key] = gender else: print("student {} exists!".format(key)) print(mydict)
this gives:
{'sonia abdull': 'f', 'sammi armstrong': 'f', 'tina barrey': 'f', 'daniel dance': 'm', 'peter huang': 'm', 'henry cheng': 'm', 'kyle bu': 'm'}
Comments
Post a Comment