2
\$\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
Sᴀᴍ Onᴇᴌᴀ
29.6k16 gold badges45 silver badges203 bronze badges
asked Apr 25, 2023 at 16:29
\$\endgroup\$

1 Answer 1

2
\$\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)
answered Apr 25, 2023 at 20:48
\$\endgroup\$
1
  • \$\begingroup\$ Thanks, i will try both solutions because i just learn Python \$\endgroup\$ Commented Apr 30, 2023 at 17:31

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.