I have block of code that calls function products_api_get_lowest_priced_offers
that may return a single record or multiple records. From that block of code I call def parse price
which will parse a record and return the fields in a dict. I did this to make things more efficient by storing the code that walks the data in one place. Instead, it gives me code that I need two very similar blocks of code that pulls the values out of the dictionary (depending if I get one or more records back). Is there a more efficient way?
def parse_price(sku_multi_sku):
parsed_results=dict();
parsed_results['ASIN'] = sku_multi_sku['Product']['Identifiers']['MarketplaceASIN']['ASIN']['value']
parsed_results['SellerSKU'] = sku_multi_sku['Product']['Identifiers']['SKUIdentifier']['SellerSKU']['value']
return parsed_results
......
......
lowest_offer = products_api.get_lowest_priced_offers_for_sku(marketplace_id, skus)
lowest_offer_dict = lowest_offer.parsed
if type(lowest_offer_dict) is list:
for sku_multi_sku in lowest_offer_dict:
results=parse_price(sku_multi_sku)
ASIN=results['ASIN']. #this block is repeated below
SKU=results['SellerSKU'] #this block is repeated below
single_insert = (ASIN, SellerSKU) #this block is repeated below
full_insert.append(single_insert) #this block is repeated below
else:
results = parse_price(sku_multi_sku)
ASIN = results['ASIN']
SKU = results['SellerSKU']
single_insert = (ASIN, SellerSKU)
full_insert.append(single_insert)
cursor.executemany("INSERT into tbl_update (ASIN, SellerSku) VALUES (%s, %s)", full_insert)
db.commit()
CodePudding user response:
You could eliminate the redundancy as follow:
# (...)
lod = lowest_offer_dict
if not isinstance(lod, list):
lod = [lod]
for sku_multi_sku in lod:
results = parse_price(sku_multi_sku)
# ...
Alternatively, you could make a companion function to parse_price
that returns a list of tuples (the ones you currently place in full_insert
):
def parse_prices_to_tuples(lod):
if not isinstance(lod, list):
lod = [lod]
tuples = [
(r['ASIN'], r['SellerSKU'])
for sku_multi_sku in lod
for r in [parse_price(sku_multi_sku)]
]
return tuples
# and in your code
full_insert = parse_prices_to_tuples(lowest_offer.parsed)