繁体   English   中英

如何将dict键与列表中对象的属性相关联?

[英]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.

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