How to update a key slice (key) of a Python dictionary?

Asked

Viewed 36 times

0

How do I update just a slice of a key in a Python dictionary? I am scraping a page and would like to format the result so that my key is on the same line as my value, for example:

Air Conditioners: https://www.consumerreports.org/cro/air-conditioners.htm

Since there are tags " n" in my dictionary (for example: {' Nair Conditioners n': '/Cro/air-conditioners.htm'...}), when I print this result, the key is on a different line from my value. That’s why I’m trying to remove only the last two characters from my keys. I tried to replace the " n" at the end of the key with "", reassigning the key variable, but I was unsuccessful. Does anyone know how I can fix this? Follow the code below:

from bs4 import BeautifulSoup
import re


def leia_arquivo():
    arquivo = open('43.consumer_reports.txt')
    dado = file.read()
    arquivo.close()
    return dado


soup = BeautifulSoup(leia_arquivo(), 'lxml')


produtos = {}   # {nome do produto: link do produto}
produtos = {a.string: a['href'] for a in soup.find_all('a', class_='products-a-z__results__item')}
print(produtos)

for key, value in produtos.items():
    if key[-2:] == '\n':
        key = key.replace('\n', '')
    print(produtos)
    print(f'{key}: https://www.consumerreports.org{value}')

I tried to use the methods of that answer: How to change the value of the key in a Python dictionary? , but I was not successful either, perhaps because it is a slice and not a replacement or total removal of the key.

  • 1

    I marked as duplicate, pq. my answer in the given question explains well what happens to rename dictionary keys, and gives the options. But in this case, the best thing is to remove the whitespace (all characters from the space category) when creating the dictionary the first time. The method .strip() strings does this - just rewrite your line that creates the dictionary as: produtos = {a.string.strip(): a['href'] for a in soup.find_all('a', class_='products-a-z__results__item')}

  • 1

    (the line above this, creating an empty dictionary is also unnecessary - the Dict-comprehension, as you are already using creates a new dictionary)

  • @jsbueno thank you so much for the fixes and for the help. It was simpler than I was thinking. I should delete this question?

  • 1

    You can leave it at that - it turns out to be another way for people to find the question that has the right answer.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.