简体   繁体   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

I have a while loop that fills a list of objects (called listofSpreadsheetRowObjects) ,and another loop that fills a dictionary associating Var1:Account2 (called dict_var1_to_account_2). 我有一个while循环,它填充了一个对象列表(称为listofSpreadsheetRowObjects),另一个循环是填充了与Var1:Account2相关联的字典(称为dict_var1_to_account_2)。 But, I need to get that dictionary's value into each object, if the key matches the object's Account1. 但是,如果键与对象的Account1匹配,则需要将该字典的值放入每个对象。

So basically, I have: 所以基本上,我有:

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

I've tried this: 我已经试过了:

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

But, it's not working, and I suspect it's my first "if" statement, because listOfSpreadsheetRowObjects is just a list of those objects, I don't think it's actually talking to the attributes of those objects in that list. 但是,它不起作用,我怀疑这是我的第一个“ if”语句,因为listOfSpreadsheetRowObjects只是这些对象的列表,我不认为它实际上是在与该列表中那些对象的属性进行通讯。 But, I've tried if any(k == item.account1 for item in listOfSpreadsheetRows): , and that doesn't seem to pull anything at all either. 但是,我尝试过是否有任何问题(k == item.account1 for listOfSpreadsheetRows中的项目):,这似乎也没有任何作用。

How would I access account1 of each object, so I can match them as needed? 我将如何访问每个对象的account1,以便可以根据需要进行匹配?

Eventually, I should have three objects with the following information: 最终,我应该拥有三个具有以下信息的对象:

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

It looks like it would be easier to iterate over the row objects first, and then for each one check if its account1 is in the dict: 看起来似乎首先要遍历行对象会更容易,然后对每个对象检查其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