【问题标题】:Python -Initializing Dictionary inside dictionary (if it doesnt exist)Python - 在字典中初始化字典(如果它不存在)
【发布时间】: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


【解决方案1】:

setdefault 是你想要的。医生说:

setdefault(key[, default])

如果键在字典中,则返回其值。如果不是,则插入值为默认值的键并返回默认值。默认默认为无。

你应该使用:

self.prices_to_request.setdefault(seller_id, {})['auth_token'] = auth_token
self.prices_to_request[seller_id].setdefault('sku', []).append(sku)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2017-11-15
    • 2020-04-09
    相关资源
    最近更新 更多