-2

So I have something like:

d = {'d':[' Cool Guy', ' Cool Gal']}

How do I remove the space inside the key-value so my output would be

d = {'d':['Cool Guy', 'Cool Gal']}

I appreciate the help, thank you.

tripleee
  • 175,061
  • 34
  • 275
  • 318

2 Answers2

2
d = {'d':[' Cool Guy', ' Cool Gal']}
for key in d:
    d[key] = [ls.strip() for ls in d[key]]
Ankit Agrawal
  • 596
  • 5
  • 12
  • 2
    There is also `.lstrip()` if you only want to remove only the leading space and ignore trailing whitespace. – monkut Nov 29 '19 at 05:59
1
d = {'d':[' Cool Guy', ' Cool Gal']}

for k, v in d.items():
    new_d = {k:[elem[1:] for elem in v]}
    print(new_d)

Output:

{'d': ['Cool Guy', 'Cool Gal']}

Logic:

  1. Extract the key (k) and corresponding value list (v).
  2. Loop through its items and ignore first character to form new array.
  3. Store new list as the new value of the dictionary.
lbragile
  • 7,549
  • 3
  • 27
  • 64