Iterate over dictionary of objects

谁说我不能喝 提交于 2020-12-26 06:21:25

问题


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 expecting sName to contain an object of type varName. But alas it contains a string. What am I doing wrong?


回答1:


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


来源:https://stackoverflow.com/questions/31007382/iterate-over-dictionary-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!