user3097421 user3097421 - 2 months ago 6x
Python Question

How can I associate a dict key to an attribute of an object within a list?

class SpreadsheetRow(object):
def __init__(self,Account1):

I have a while loop that fills a list of objects ,and another loop that fills a dictionary associating Account1:Account2. But, I need to get that dictionary's value into each object, if the key matches Account1.

So basically, I have:

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

I've tried this:

for k, v in dict_of_account1_to_account2.iteritems():
if k in listOfSpreadsheetRowObjects:
if self.account1=k:

But, it's not working, and I suspect it's my first "if" statement, because listOfSpreadsheetRowObjects is just a list of those objects. How would I access account1 of each object, so I can match them as needed?


You can use a generator expression within any() to check if any account1 attribute of those objects is equal with k:

if any(k == item.account1 for item in listOfSpreadsheetRows):