Adding and accessing values to key in python dictionary -
i'm writing python script reads players name , stats sentence in .txt file, updates stats within dictionary , prints out average stats. i'm having problem assigning multiple values same 'player' key, getting logic below correctly update player stats. .group part giving me problem too. how can this?
import re, sys, os, math if len(sys.argv) < 2: sys.exit("usage: %s filename" % sys.argv[0]) filename = sys.argv[1] if not os.path.exists(filename): sys.exit("error: file '%s' not found" % sys.argv[1]) line_regex = re.compile(r"^(\w+ \w+) batted (\d+) times (\d+) hits , (\d+) runs") line = [line.strip() line in open(filename)] f = open (filename) playerstats = {'players': [0, 0, 0]} players in playerstats: player = line.group(1) atbat = line.group(2) nail = line.group(3) if player in playerstats: playerstats[player][0] += atbat playerstats[player][1] += nail if player not in players: player = line.group(1) playerstats[player][0] = atbat playerstats[player][1] = nail avgs = 0 else: playerstats[player][0] = player playerstats[player][0] = atbat playerstats[player][1] = nail playerstats[player][2] = 0 player in players: avgs[player] = round(float(hits[player])/float(atbats[player]), 3) print "%s: %.3f" % (player, avgs[player])
traceback (most recent phone call last): file "ba.py", line 19, in player = line.group(1) attributeerror: 'list' object has no attribute 'group'
you should alter this
playerstats = {'players': hits, atbats, avgs}
to
playerstats = {'players': [0, 0, 0]}
the latter stores value list
, former not valid python syntax.
to modify 1 of these values do, example
playerstats[player][1] = 5 # atbat value
you alter nested construction like
playerstats = {'players': {'hits' : 0, 'atbats' : 0, 'avgs' : 0)}
then modify values as
playerstats[player]['hits'] = 3
python dictionary
No comments:
Post a Comment