Skip to content
List pairing

List pairing

Zip two scraped lists into a dict

When a page renders two related columns, each column can be collected into its own list. zip(names, prices) pairs the first name with the first price, the second name with the second price, and so on. dict() converts those pairs into a dictionary in which each name is a key and its corresponding price is the value.

The pairing is positional rather than based on HTML relationships. Both lists must therefore be collected in the same document order and contain the same number of relevant entries.

names = []
for t in soup.find_all("h3"):
    names.append(t.get_text(strip=True))

prices = []
for d in soup.select("section.list > div"):
    for t in d.stripped_strings:
        if t.startswith("$"):
            prices.append(t)

item_pairs = zip(names, prices)
items = dict(item_pairs)
for name, price in items.items():
    print(f"{name}: {price}")

Sample markup

<section class="list">
  <div><h3>Laptop</h3><span>$1,299</span></div>
  <div><h3>Mouse</h3><span>$25</span></div>
</section>

Example output

Laptop: $1,299
Mouse: $25

Find by: zip, dict, combine lists, pair, names and prices, mapping, dictionary · Source: WSA SQLi in-band