繁体   English   中英

如何将特定的字典键与类列表中的对象相关联?

[英]How can I associate a specific dictionary key to an object in a list of classes?

class SpreadsheetRow(object):
    def __init__(self,Account1):
        self.Account1=Account1
        self.Account2=0

我有一个while循环,它填充了一个对象列表(称为listofSpreadsheetRowObjects),另一个循环是填充了与Var1:Account2相关联的字典(称为dict_var1_to_account_2)。 但是,如果键与对象的Account1匹配,则需要将该字典的值放入每个对象。

所以基本上,我有:

listofSpreadsheetRowObjects=[SpreadsheetRow1, SpreadsheetRow2, SpreadsheetRow3]
dict_var1_to_account2={1234:888, 1991:646, 90802:5443}

我已经试过了:

for k, v in dict_var1_to_account2.iteritems():
    if k in listOfSpreadsheetRowObjects:
        if account1=k:
              account2=v

但是,它不起作用,我怀疑这是我的第一个“ if”语句,因为listOfSpreadsheetRowObjects只是这些对象的列表,我不认为它实际上是在与该列表中那些对象的属性进行通讯。 但是,我尝试过是否有任何问题(k == item.account1 for listOfSpreadsheetRows中的项目):,这似乎也没有任何作用。

我将如何访问每个对象的account1,以便可以根据需要进行匹配?

最终,我应该拥有三个具有以下信息的对象:

SpreadsheetRow 
self.Account1=Account1 
self.Account2=(v from my dictionary, if account1 matches the key in my dictionary)

看起来似乎首先要遍历行对象会更容易,然后对每个对象检查其account1是否在dict中:

for row in listofSpreadsheetRowObjects:
    if row.Account1 in dict_var1_to_account2:
        row.Account2 = dict_var1_to_account2[row.Account1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM