[英]How can I associate a specific dictionary key to an object in a list of classes?
[英]How can I associate a dict key to an attribute of an object within a list?
class SpreadsheetRow(object):
def __init__(self,Account1):
self.Account1=Account1
self.Account2=0
我有一个while循环填充一个对象列表,另一个循环填充一个关联Var1:Account2的字典。 但是,如果密钥与对象的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 self.account1=k:
self.account2=v
但是,它不起作用,我怀疑它是我的第一个“if”语句,因为listOfSpreadsheetRowObjects只是这些对象的列表。 我如何访问每个对象的account1,以便根据需要匹配它们?
最后,我应该有三个对象,其中包含以下信息:SpreadsheetRow self.Account1 = Account1 self.Account2 =(v from my dictionary,如果account1与我字典中的键匹配)
您可以在any()
使用生成器表达式来检查这些对象的任何account1
属性是否与k
相等:
if any(k == item.account1 for item in listOfSpreadsheetRows):
您可以尝试使用next
函数:
next(i for i in listOfSpreadsheetRows if k == i.account1)
如果您有一个字典d
并希望获得与键x
相关联的值,那么您可以像这样查找该值:
v = d[x]
因此,如果你的字典被称为dict_of_account1_to_account2
并且密钥是self.Account1
并且你想将该值设置为self.Account2
那么你会这样做:
self.Account2 = dict_of_account1_to_account2[self.Account1]
使用字典的重点在于,您不必遍历整个事物来查找内容。
否则,如果在创建所有SpreadsheetRow
对象后对.Account2
进行初始化,那么使用self
是没有意义的,您需要遍历每个SpreadsheetRow
项并为每个项执行赋值,如下所示:
for row in listofSpreadsheetRowObjects:
for k, v in dict_of_account1_to_account2.iteritems():
if row.Account1 == k:
row.Account2 = v
但同样,你不必迭代字典来进行赋值,只需从字典中查找row.Account1
:
for row in listofSpreadsheetRowObjects:
row.Account2 = dict_of_account1_to_account2[row.Account1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.