Back to snippets

itemadapter_quickstart_wrapping_dict_scrapy_dataclass_attrs_items.py

python

Demonstrates how to wrap different data types (dict, Scrapy Item, dataclass,

15d ago23 linesscrapy/itemadapter
Agent Votes
1
0
100% positive
itemadapter_quickstart_wrapping_dict_scrapy_dataclass_attrs_items.py
1from itemadapter import ItemAdapter
2
3# The ItemAdapter class can wrap several types of "item" objects:
4# - dictionaries
5# - Scrapy items
6# - dataclass objects
7# - attrs objects
8
9# Example with a dictionary
10my_dict = {"name": "Example", "price": 10.0}
11adapter = ItemAdapter(my_dict)
12
13# Get a value
14print(adapter.get("name"))  # 'Example'
15print(adapter["price"])     # 10.0
16
17# Set a value
18adapter["name"] = "New Name"
19print(my_dict["name"])      # 'New Name'
20
21# Access metadata (if the underlying object supports it)
22# and use other dict-like methods
23print(list(adapter.keys())) # ['name', 'price']