newbie needs help on dictionary
Fredrik Lundh
fredrik at pythonware.com
Fri Dec 10 04:16:57 EST 1999
Matthew Miller <matthewm at es.co.nz> wrote:
> i've created a list of 20 dictionaries thus...
>
> turret = [{}] * 20
that's a list of 20 references to the same
dictionary.
>>> turret = [{}] * 20
>>> turret
[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
>>> turret[0]["foo"] = 1
>>> turret
[{'foo': 1}, {'foo': 1}, {'foo': 1}, {'foo': 1}, {'foo': 1}, {'foo': 1}, {'foo':
1}, {'foo': 1}, {'foo': 1}, {'foo': 1}, {'foo': 1}, {'foo': 1}, {'foo': 1}, {'f
oo': 1}, {'foo': 1}, {'foo': 1}, {'foo': 1}, {'foo': 1}, {'foo': 1}, {'foo': 1}]
see:
http://www.python.org/doc/FAQ.html#4.50
for some background.
> then scans text-files for tooling information and add entries to a
> certain dictionary in list via
>
> turret[station][tool_name] = 1
>
> my question is how do you increment the value accessed by the key. all
> i've been able to figure is
>
> count = turret[station][tool_name]
> count = count + 1
> turret[station][tool_name] = count
how about:
s = turret[station]
s[tool_name] = s.get(tool_name, 0) + 1
</F>
More information about the Python-list
mailing list