Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing special characters from dictionary

I am trying to remove all the \r\n from the python dictionary. What is the easiest way to do so. My dictionary is looking like this at the moment -

 {'': '34.8\r\n', 
  'Mozzarella di Giovanni\r\n': '34.8\r\n', 
   'Queso Cabrales\r\n': '14\r\n', 
   'Singaporean Hokkien Fried Mee\r\n': '9.8\r\n'
}

EDIT : Here's what I'm trying -

for key, values in productDictionary.items() :
    key.strip()
    values.strip()
    key.strip('"\"r')
    key.strip('\\n')
    values.strip('\\r\\n')
print productDictionary

And the output is still the same.

like image 729
Ashish Agarwal Avatar asked May 16 '26 01:05

Ashish Agarwal


1 Answers

Using a dictionary comprehension:

clean_dict = {key.strip(): item.strip() for key, item in my_dict.items()}

The strip() function removes newlines, spaces, and tabs from the front and back of a string.

like image 134
Michael0x2a Avatar answered May 19 '26 03:05

Michael0x2a