遍历对象字典 [英] Iterate over dictionary of objects
问题描述
我有一个对象字典,其中包含名称/范围"在电子表格中.在处理电子表格时,我需要更新与范围相关联的值.
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.
保存此信息的类如下:
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
我创建字典如下:
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
引用包含Name/Range对象的字典.我期望 sName
包含 varName
类型的对象.但是可惜它包含一个字符串.我在做什么错了?
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?
推荐答案
for some_dict
中的foo遍历字典的 keys ,而不是字典的值.
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
您可能想对some_dict.values()中的foo做
You probably want to do for foo in some_dict.values()
for dd in d.values():
print(dd)
# gives 1; 2; 3
这篇关于遍历对象字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!