Ganga
Ganga

Reputation: 305

Remove space in keys of a dictionary

d={'A ':[],'B '=[]}

I want to remove the whitespace before the quote and produce the following:

d={'A':[],'B'=[]}

for k,v in d.items():
    k=k.replace(" ","")
pprint.pprint(d)

I expect the above code to remove space before the quote,but the output is same as previous dictionary I also tried k=k.strip(),which produced the same result

I will be thankful if somebody can suggest me the solution

Upvotes: 1

Views: 56

Answers (3)

Sufiyan Ghori
Sufiyan Ghori

Reputation: 18753

you can create a new dict object with modified keys,

d={'A ':[],'B ':[]}

d = dict((k.strip(), v) for k, v in d.items())
print(d)

Upvotes: 2

kellymandem
kellymandem

Reputation: 1769

First of all there is error in your declaration of the dictionary, as in this

d={'A ':[],'B '=[]}

needs to be changed to this

d={'A ':[],'B ':[]}

As for your answer, you could try creating a new dictionary

from pprint import pprint
d={'A ':[],'B ':[]}
new_d = {}

for k, v in d.items():
    new_d[k.strip()] = v

pprint(new_d)

Upvotes: 0

Vaibhav Vishal
Vaibhav Vishal

Reputation: 7108

Try this:

>>> d={'A ':[],'B ':[]}
>>> new_d ={}
>>> for k, v in d.items():
        new_d[k.strip()] = v


>>> d
{'A ': [], 'B ': []}
>>> new_d
{'A': [], 'B': []}

btw, you have syntax error in your question. Your are writing 'B '=[] instead of 'B ': []

Upvotes: 1

Related Questions