【发布时间】:2022-01-24 12:07:45
【问题描述】:
我有下面的代码,我试图为每个卖家 ID 创建一个字典,为每个卖家存储一个 auth_token,然后存储一个 skus 列表。我的问题是:
1 - 此代码在每次通过时重新初始化 Seller_id 记录。我不知道如何将其转至create the record for this seller only if it doesnt exist
self.prices_to_request.update({(seller_id): {}})
2 - self.prices_to_request[seller_id].setdefault('sku', []).append(sku) 是不是比我的 try 声明更好的替代品?它似乎有效,但我无法完全测试它,因为代码在每次通过时都会重新初始化 seller_id
代码
def add(self, seller_id, auth_token, sku):
self.prices_to_request.update({(seller_id): {}})
self.prices_to_request[seller_id]['auth_token'] = auth_token
try:
self.prices_to_request[seller_id]['sku'].append(sku)
except KeyError:
self.prices_to_request[seller_id]['sku'] = []
self.prices_to_request[seller_id]['sku'].append(sku)
【问题讨论】:
-
使用
defaultdict(dict)? -
字典上的
keys()函数返回字典中所有键的列表。只需检查键是否在该列表中,如果没有则将其添加到字典中。
标签: python list dictionary