Keeping track of things with dictionaries

Giuliano Bertoletti gbe32241 at libero.it
Sun Apr 6 03:44:13 EDT 2014


I frequently use this pattern to keep track of incoming data (for 
example, to sum up sales of a specific brand):

=====================================

# read a brand record from a db
...

# keep track of brands seen
obj = brands_seen.get(brandname)
if obj is None:
    obj = Brand()
    brands_seen[brandname] = obj

obj.AddData(...)	# this might for example keep track of sales

=====================================

as you might guess, brands_seen is a dictionary whose keys are 
brandnames and whose values are brand objects.

Now the point is: is there a cleverer way to do this?

Basically what I'm doing is query the dictionary twice if the object 
does not exist.

What I would like to understand is if there's some language built-in 
logic to:

- supply a function which is meant to return a new object
- have the interpreter to locate the point in the dictionary where the 
key is to be
- if the key is already there, it returns the value/object associated 
and stops
- if the key is not there, it calls the supplied function, assigns the 
returned value to the dictionary and return the object.

Giulio.













More information about the Python-list mailing list