-1

I have a dictionary and I need to remove one whitespace at the beginning of the result value.

dct = {   
    'data': '',
    'order': 100,
    'result': ' home page',
    'step': 'click'
}

So it will end up looking like this:

dct = {   
    'data': '',
    'order': 100,
    'result': 'home page',
    'step': 'click'
}
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • Does this answer your question? [Iterating over a dictionary in python and stripping white space](https://stackoverflow.com/q/8907788/6045800) – Tomerikoo Jan 20 '22 at 19:00

2 Answers2

0

Just .strip() the values if they are strings. Here is the dictionary comprehension approach:

dct = {
    'data': '',
    'order': 100,
    'result': ' home page',
    'step': 'click'
}

dct = {k: v.strip() if isinstance(v, str) else v for k, v in dct.items()}
print(dct)

output:

{'data': '', 'order': 100, 'result': 'home page', 'step': 'click'}

.strip() will remove whitespaces from both left and right side of the string. If you need it to remove the left whitespaces only, you can use .lstrip() instead.

S.B
  • 13,077
  • 10
  • 22
  • 49
0

You can do that with the following

for key in dct:
    if type(dct[key]) == str:
        dct[key] = dct[key].strip()
BoomBoxBoy
  • 1,770
  • 1
  • 5
  • 23