faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 4 people (75%) answered Yes
Recently 2 of 3 people (67%) answered Yes

Entry

Increasing dict values

Jul 5th, 2000 10:03
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 383, Fredrik Lundh


"""
Packages: basic_datatypes.dictionaries
"""

"""
> i've created a list of 20 dictionaries thus...
> 
> turret = [{}] * 20

that's a list of 20 references to the same
dictionary.

> 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