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

时间:2016-08-01 17:28:29

标签: python dictionary

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只是这些对象的列表,我不认为它实际上是在与该列表中的那些对象的属性进行对话。但是,我试过了 如果有的话(对于listOfSpreadsheetRows中的item,k == item.account1):,那似乎根本没有任何东西。

我如何访问每个对象的account1,以便根据需要匹配它们?

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

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

1 个答案:

答案 0 :(得分:0)

看起来首先迭代行对象会更容易,然后检查每个行对象的account1是否在dict中:

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