4

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']}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
GreyTek
  • 89
  • 1
  • 1
  • 6
  • Do you want to edit the existing dictionary or create a new dictionary? Does anything need to be done about colliding keys? – Jared Goguen Mar 02 '16 at 21:55
  • All of the keys are unique, ideally the spaces would be removed from the existing dictionary keys. – GreyTek Mar 02 '16 at 21:58

4 Answers4

12

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())
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
4

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())
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

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']}
Vader
  • 3,675
  • 23
  • 40
1

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.

Jared Goguen
  • 8,772
  • 2
  • 18
  • 36