# It can be useful to iterate through data contained # in your own custom objects. # Lets say you have your own class class ExampleClass(object): def __init__(self): self.objectList = [] self.objectDict = {} self.maxItem = 100 self.objectItem = "" def iterateList(self): return self.objectList def addListItem(self, item): self.objectList.append(item) def addDictItem(self, item, value): self.objectDict[item] = value # create an instance of the class # and lets use it's iterating methods ec = ExampleClass() # add some example data for i in xrange(10): ec.addListItem(i) ec.addDictItem(i, str(i)+"'s value") # now that we have data lets iterate # through the data for item in ec.iterateList(): print item #output: # 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9
A python example based blog that shows how to accomplish python goals and how to correct python errors.
Showing posts with label iterate. Show all posts
Showing posts with label iterate. Show all posts
Sunday, October 4, 2009
Python - make your own class attributes iterable
Wednesday, July 8, 2009
python dict
# a dictionary is created with curly braces {}
>>> d = {}
>>> type(d)
# add key,value pairs to the dict
>>> d['adam'] = 123422
>>> d['barry'] = 234223
>>> d['charlie'] = 999322
>>> d
{'barry': 234223, 'adam': 123422, 'charlie': 999322}
# test whether keys are in a dict
>>> 'steve' in d
False
>>> 'barry' in d
True
# iterate through a dict's keys
>>> for k in d.iterkeys():
... print k
...
barry
adam
charlie
# get a key's value from the dict
>>> d.get(k)
999322
# iterate through keys and print out key, value
>>> for k in d.iterkeys():
... print k, " = ", d.get(k)
...
barry = 234223
adam = 123422
charlie = 999322
# more detailed info on python dict: http://docs.python.org/library/stdtypes.html#mapping-types-dict
Subscribe to:
Posts (Atom)