Search code examples
pythonpython-3.xtrim

Python3 trim all data from associative array


I'm using Python3 and I tried all way of this question but no one solution works. If I do this way list(map(str.strip, my_list)) I lost all my keys because list() return just values accessible just with indice.

So I decided to trim manually with .strip() all my data but it will not work for NoneType data. I don't want to do 30 conditions...

if str:
   str.strip(' ')

So do you have a solution to trim all str value in my associative array ? My array can content None, Int and String.


Solution

  • I'll assume that when you say "associative array" you actually mean a Python dict.

    >>> d = { 'a': 'foo\n', 'b': 3, 'c': None }
    >>> cleaned = { k: v.strip() if isinstance(v, str) else v for k,v in d.items() }
    >>> cleaned
    {'b': 3, 'a': 'foo', 'c': None}