0
\$\begingroup\$

I need to store data in Scrapy Item in parts. To update only the information that I found at the moment.

I did it, but the code looks too verbose. Three lines I repeat very often:

price['pricereg'] = pricereg
price['priceprolong'] = priceprolong 
price['pricechange'] = pricechange 

Is it possible to make the code shorter?

EMPTY_PRICE = {
        'pricereg': None,
        'priceprolong': None,
        'pricechange': None,
    }

item['name'] = "some name"
        price = item.get('price', EMPTY_PRICE)
        price['pricereg'] = pricereg
        price['priceprolong'] = priceprolong
        item['price'] = price

item['name'] = "some name"  
        price = item.get('price', EMPTY_PRICE)
        price['pricechange'] = pricechange 
        item['price'] = price
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Have you tried using a collections.namedtuple or a dataclasses.dataclass rather than a dict?

from collections import namedtuple

Item = namedtuple('Item', ['name', 'pricereg', 'priceprolong', 'price'],
                  defaults=['', None, None, None])

EMPTY_ITEM = Item()
item['name'] = Item('name', pricereg, priceprolong, price)

print(item['name']._asdict())

or

from dataclasses import dataclass

@dataclass
class Item:
    name: str
    pricereg: int|None = None
    priceprolong: int|None = None
    price: int|None = None

EMPTY_ITEM = Item()
item['name'] = Item('name', pricereg, priceprolong, price)

print(item['name'].pricereg)

alternatively, if you're just setting the dict in one go:

item['name'] = {'pricereg': pricereg, 
                'priceprolong': priceprolong,
                'pricechange': pricechange if pricechange else None, # For defaults 
                'price': price}

If it's to do with setting it up in parts, you can build the dict with the parts you have and do a dict.update

item['name'] = {'pricereg': pricereg, 
                'priceprolong': priceprolong}

tmp = {
       'pricechange': pricechange if pricechange else None, # For defaults 
       'price': price}
item['name'].update(tmp)
\$\endgroup\$
1
  • \$\begingroup\$ Thanks, i will try both solutions because i just learn Python \$\endgroup\$
    – MariaCurie
    Commented Apr 30, 2023 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.