[Tutor] Re: Using a dictionary to keep a count
Karl Pflästerer
sigurd at 12move.de
Thu Aug 7 03:29:38 EDT 2003
On 4 Aug 2003, Levy Lazarre <- levy.lazarre at mfms.com wrote:
> Thanks for the clarification and suggestion, however this approach doesn't
> work for it doesn't create the intended dictionary of dictionaries
> structure.
Sorry I overlooked that need.
[...]
> The following approach using exceptions seems to work:
> ###############################################
> dic ={}
Try to avoid global variables whenever possible.
[Code with try/except]
> Any comments? Is this a bad style? I was trying to make the code shorter
> with setdefault(), but it appears very difficult to use with nested
> structures.
No code with try/except is most of the times good style. Here is an
example how your desire could be achieved with setdefault.
def process_log_file(name):
d = {}
f = open(name)
for line in f:
script, address = process_line(line)
d.setdefault(script, {})
d[script][address] = d[script].setdefault(address,0) + 1
f.close()
for (key, value) in d.items():
print key , '=>'
for (subkey, subvalue) in value.items():
print ' ' * len(key + '=<'), subkey, ': ', subvalue
You could write the assignment in one line but I wouldn't recommend it
(unless you like unreadable code):
def process_log_file(name):
d = {}
f = open(name)
for line in f:
script, address = process_line(line)
d[script][address] = d.setdefault(script, {}).setdefault(address,0) + 1
f.close()
for (key, value) in d.items():
print key , '=>'
for (subkey, subvalue) in value.items():
print ' ' * len(key + '=<'), subkey, ': ', subvalue
You could separate the printing part in the above function but I didn't
do that because the format is very specific.
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list