How to retrieve an object from a Python Dictionary -
i'm trying retrieve object i've placed dictionary, every time try retrieve receive error:
class csventry: lat = [] lon = [] count = 0 # create dictionary tracking inputs dict = defaultdict(list) # lookup zipcode (returns integer value) zipcode = convertlatlontozip(row[latcol], row[loncol]) # if zipcode in dictionary, update new count if zipcode in dict: oldentry = dict[zipcode] oldentry.lat.append(row[latcol]) oldentry.lon.append(row[loncol]) oldentry.count = dict[zipcode].count + 1 # otherwise, make new entry else: entry = csventry() entry.lat.append(row[latcol]) entry.lon.append(row[loncol]) entry.count = 1 # hash on zipcode dict[zipcode].append(entry) it has no problem inserting entries dictionary, finds duplicate, fails error:
traceback (most recent call last): file "parsecsv.py", line 125, in <module> oldentry.lat.append(row[latcol]) attributeerror: 'list' object has no attribute 'lat' i apologize if duplicate or ridiculously simple question. i'm beginner python , searched long while before deciding post.
edit: added definition of dict
right oldentry list. looks want change
if zipcode in dict: oldentry = dict[zipcode] oldentry.lat.append(row[latcol]) oldentry.lon.append(row[loncol]) oldentry.count = dict[zipcode].count + 1 to
if zipcode in dict: oldentry = dict[zipcode][0] oldentry.lat.append(row[latcol]) oldentry.lon.append(row[loncol]) oldentry.count += 1 that being said, might make more sense create new csventry object , append dict[zipcode] alternatively, make dict defaultdict containing csventry objects, meaning wouldn't have check whether zipcode in dict. give code like:
zip_dict = collections.defaultdict(csventry) zip_dict[zipcode].lat.append(row[latcol]) zip_dict[zipcode].lon.append(row[longcol]) zip_dict[zipcode].count += 1 this easiest way solve problem. on sidenote, want avoid naming variable dict overwrites builtin dict type.
Comments
Post a Comment