0

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.

John
  • 4,711
  • 9
  • 51
  • 101
  • Could you give an example of your input? We can only presume that by "_associative array_" you mean "_dict_". – Attie Sep 05 '18 at 11:47

1 Answers1

3

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}
Duncan
  • 92,073
  • 11
  • 122
  • 156
  • It works thank you so much. When I search `Python trim dictionary` I can find lot of answers too. But I'll not delete my question because if someone try to search the solution with the `associative array` term like me. – John Sep 05 '18 at 12:50