Dhruva Hein wrote: > Hi. I am trying to understand a section of code written for Plone and I > am having problems understanding the Python syntax in a few of the > following lines. > > I'd be grateful if someone could help me understand what's happening in > the lines I've marked. I can't see how the dictionary is built or how > the lists ['bytype'][cytype] make sense in python. > > Thanks in advance. > > class Stats: > > def getContentTypes(self): > """ Returns the number of documents by type """ > pc = getToolByName(self, "portal_catalog") > # call the catalog and loop through the records > results = pc() > <=== what is the difference between pc and pc()?
pc refers to an object, pc() calls it. in this case, it looks like pc is the portal catalog, and calling the catalog returns the contents. > numbers = {"total":len(results),"bytype":{},"bystate":{}} <=== > This is hard to understand that line creates a dictionary with three members. you have read the Python tutorial, right? the code above is equivalent to: numbers = {} numbers["total"] = len(results) numbers["bytype"] = {} numbers["bystate"] = {} where {} creates a new, empty dictionary. > for result in results: > # set the number for the type > ctype = str(result.Type) > num = numbers["bytype"].get(ctype, 0) <==== where does .get > come from? and what is the string 'bytype' doing? "bytype" is a dictionary key, so numbers["bytype"] fetches a dictionary from the numbers dictionary (see above). get is a dictionary method; it returns the value corresponding to the given key (ctype), or a default value (0) if the key does not exist. that last line is equivalent to temp = numbers["bytype"] if temp.has_key(ctype): num = temp[ctype] else: num = 0 > num += 1 > numbers["bytype"][ctype] = num <====== is this some kind > of an array? no, it's a dictionary that contains a dictionary. that line is equi- valent to temp = numbers["bytype"] temp[ctype] = num for more on dictionaries, see the Python tutorial. > # set the number for the state > state = str(result.review_state) > num = numbers["bystate"].get(state, 0) > num += 1 > numbers["bystate"][state] = num > return numbers hope this helps! </F> -- http://mail.python.org/mailman/listinfo/python-list