Ashish Agarwal
Ashish Agarwal

Reputation: 14925

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.

Upvotes: 2

Views: 20489

Answers (2)

Michael0x2a
Michael0x2a

Reputation: 64118

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.

Upvotes: 9

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250971

you can use str.strip():

str.strip() when used with no arguments, strips all types of leading and trailing whitespaces.

>>> productDictionary={'': '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'
}

>>> productDictionary=dict(map(str.strip,x) for x in productDictionary.items()) 
>>> print productDictionary
>>>
{'': '34.8',
 'Mozzarella di Giovanni': '34.8',
 'Queso Cabrales': '14',
 'Singaporean Hokkien Fried Mee': '9.8'}

help() on str.strip()

S.strip([chars]) -> string or unicode

Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping

Upvotes: 7

Related Questions