GreyTek
GreyTek

Reputation: 89

Remove space from dictionary keys

I have a dictionary with keys/values such as:

{'C  14': ['15263808', '13210478'], 'W   1': ['13122205']}

How can I remove the white space from all of the keys so they instead would be:

{'C14': ['15263808', '13210478'], 'W1': ['13122205']}

Upvotes: 4

Views: 13298

Answers (4)

Martijn Pieters
Martijn Pieters

Reputation: 1122312

You can process all keys in a dictionary comprehension; you could use str.translate() to remove the spaces; the Python 2 version for that is:

{k.translate(None, ' '): v for k, v in dictionary.iteritems()}

and the Python 3 version is:

{k.translate({32: None}): v for k, v in dictionary.items()}

You could also use str.replace() to remove the spaces:

{k.replace(' ', ''): v for k, v in dictionary.items()}

But this may be slower for longer keys; see Python str.translate VS str.replace

Note that these produce a new dictionary.

Demo on Python 2:

>>> d = {'C  14': ['15263808', '13210478'], 'W   1': ['13122205']}
>>> {k.translate(None, ' '): v for k, v in d.iteritems()}
{'W1': ['13122205'], 'C14': ['15263808', '13210478']}

And a 2.6 compatible version (using Alternative to dict comprehension prior to Python 2.7):

dict((k.translate(None, ' '), v) for k, v in dictionary.iteritems())

Upvotes: 12

Jared Goguen
Jared Goguen

Reputation: 9010

Here's a solution without a dict comprehension, that edits the dictionary in-place, and assumes that no two old keys will map to the same new key.

d = {'C  14': ['15263808', '13210478'], 'W   1': ['13122205']}

for key in d.keys():
    if ' ' in key:
        d[key.translate(None, ' ')] = d[key]
        del d[key]

print d # {'W1': ['13122205'], 'C14': ['15263808', '13210478']}

After some timing, this is about 25% quicker than creating a new dictionary.

The loop iterates over d.keys() rather than d directly to avoid revisiting keys and avoid the whole "iterating over a changing object" issue.

Upvotes: 1

Vader
Vader

Reputation: 3883

Without dict comprehension:

>>> d = {'C  14': ['15263808', '13210478'], 'W   1': ['13122205']}
>>> dict(((k.replace(' ',''),v) for k,v in d.items()))
{'W1': ['13122205'], 'C14': ['15263808', '13210478']}

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

You can also just use str.replace:

In [4]: d = {'C  14': ['15263808', '13210478'], 'W   1': ['13122205']}

In [5]: d = {k.replace(" ",""): v for k,v in d.items()}

In [6]: d
Out[6]: {'C14': ['15263808', '13210478'], 'W1': ['13122205']}

For python2.6:

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

Upvotes: 4

Related Questions