Home > Back-end >  Python -Initializing Dictionary inside dictionary (if it doesnt exist)
Python -Initializing Dictionary inside dictionary (if it doesnt exist)

Time:12-24

I have the code below that I am attempting to create a dictionary for each seller_id, store one auth_token for each seller and then store a list of skus. My issues are:

1 - This code re-inits the seller_id record on each pass. I am not sure how to turn this in to create the record for this seller only if it doesnt exist

self.prices_to_request.update({(seller_id): {}}) 

2 - Is self.prices_to_request[seller_id].setdefault('sku', []).append(sku) a better replacement then my try statement? It seems to work but I cant totally test it due to the fact tha the code re-inits the seller_id on each pass

Code

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)

CodePudding user response:

setdefault is what you want. The doc says:

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

You should use:

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