python - How to read from a file into a dict with string key and tuple value? -
for assignment, i'm creating program retrieves file information regarding olympic countries , medal count.
one of functions goes through list in format:
country,games,gold,silver,bronze afg,13,0,0,2 alg,15,5,2,8 arg,40,18,24,28 arm,10,1,2,9 anz,2,3,4,5 the function needs go through list, , store dictionary country name key, , remaining 4 entries tuple.
here working far:
def medals(string): '''takes file, , gathers country codes , medal counts storing them dictionary''' #creates empty dictionary medaldict = {} #creates empty tuple medalcount = () #these following 2 lines remove column headings open(string) fin: next(fin) eachline in fin: code, medal_count = eachline.strip().split(',',1) medaldict[code] = medal_count return medaldict now, intent entries this
{'afg': (13, 0, 0, 2)} instead, i'm getting
{'afg': '13,0,0,2'} it looks being stored string, , not tuple.
medaldict[code] = medal_count line of code? i'm not sure how convert separate integer values tuple neatly.
you storing whole string '13,0,0,2' value, so
medaldict[code] = medal_count should replaced by:
medaldict[code] = tuple(medal_count.split(',')) your original thought correct, line being sole exception. changed splits '13,0,0,2' list ['13', '0', '0', '2'] , converts tuple.
you can convert strings inside integers:
medaldict[code] = tuple([int(ele) ele in medal_count.split(',')]) but make sure medal_count contains integers.
Comments
Post a Comment