Iterate over dictionary of objects
for foo in some_dict
iterates through the keys of a dictionary, not its values.
d = {'a': 1, 'b': 2, 'c': 3}
for dd in d:
print(dd)
# gives a; b; c
You probably want to do for foo in some_dict.values()
for dd in d.values():
print(dd)
# gives 1; 2; 3
KBD
Updated on August 06, 2022Comments
-
KBD over 1 year
I have a dictionary of objects which contains the "Names/Ranges" within a spreadsheet. As I process the spreadsheet I need to update the value associated with a range.
The class to hold this info looks like this:
class varName: name = None refersTo = None refersToR1C1 = None value = None def __init__(self, name, refersTo, refersToR1C1, value): self.name = name self.refersTo = refersTo self.refersToR1C1 = refersToR1C1 self.value = value
I create the dictionary as follows:
staticNames = {} wbNames = wb.Names for name in wbNames: (nSheet, nAddr) = name.RefersTo.split("!") print "Name: %s Refers to: %s Refers to R1C1: %s Value: %s " % (name.Name, name.RefersTo, name.RefersToR1C1, wSheets(nSheet.replace('=', '')).Range(nAddr).value) staticNames[name.Name] = varName(name.Name, name.RefersTo, name.RefersToR1C1, wSheets(nSheet.replace('=', '') ).Range(nAddr).value)
It seems to work fine. I can see the dictionary and contained objects in debug. When I go back to update the objects within the dictionary based on processing the spreadsheet, I get lost. I call this function:
def updateStaticNames(ws, r, c, val_in, staticNames): for sName in staticNames: if sName.refersToR1C1() == "=" + ws.Name + "!R" + str(r) + "C" + str(c): sName.value = val_in return None
staticNames
refers to the dictionary containing the Name/Range objects. I am expectingsName
to contain an object of typevarName
. But alas it contains a string. What am I doing wrong?