python - TypeError: 'collections.defaultdict' object is not callable -
i having error when tried print objects in index.. trying search lname , print object values...
from collections import defaultdict class pbook(object): lname_index = defaultdict(list) def __init__(self, lname, fname, age): self.lname=lname self.fname=fname self.age=age pbook.lname_index[lname].append(self) def __str__(self): return "%s %s %s" % (self.lname, self.fname, self.age) mylist = [] mylist.append(pbook("john","smith",23)) mylist.append(pbook("george","bush",25)) print pbook.lname_index defaultdict(, {'bush': [<main.pbook object @ 0x000000000585ec50>], 'smith': [<main.pbook object @ 0x000000000585ec88>]})
if "bush" in pbook.lname_index: print "found" found
if "bush" in pbook.lname_index: print pbook.lname_index(mylist) typeerror: 'collections.defaultdict' object not callable
mylist of datatype
list. can never used key dictionary. thumb rule keys should hashable, hence use dictionary keysstring,numbersortuplesimmutable.as pointed dict should accessed
[]or using.get().
sample code
from collections import defaultdict class pbook(object): lname_index = defaultdict(list) def __init__(self, lname, fname, age): self.lname=lname self.fname=fname self.age=age pbook.lname_index[lname].append(self) def __str__(self): return "%s %s %s" % (self.lname, self.fname, self.age) mylist = [] mylist.append(pbook("john","smith",23)) mylist.append(pbook("george","bush",25)) print pbook.lname_index.get("john") print pbook.lname_index.get("george") print pbook.lname_index.get("bush", none)
Comments
Post a Comment