spoke
spoke

Reputation: 267

Convert key from dictionary to int in python

I have the following dictionary:

 d = {
  u'71': u' 12.3/0.2mm',
  u'70': u' 12.1/0.2mm', 
  u'79': u' 13.9/0.2mm', 
  u'78': u' 13.7/0.2mm'
 }

The keys are currently strings. How can I convert them to integers?

I've tried with d = {int(k) for k in d} but it messed up the dictionary, returning only the keys.

Upvotes: 2

Views: 3036

Answers (4)

Mike Müller
Mike Müller

Reputation: 85442

You can also work on the dictionary without creating a new one, using the pop() method:

for k in d:
    d[int(k)] = d.pop(k)

Example:

>>> d = {u'71': u' 12.3/0.2mm',
         u'70': u' 12.1/0.2mm', 
         u'79': u' 13.9/0.2mm', 
         u'78': u' 13.7/0.2mm'}

>>> for k in d:
        d[int(k)] = d.pop(k)
>>> d
{70: u' 12.1/0.2mm', 71: u' 12.3/0.2mm', 78: u' 13.7/0.2mm', 79: u' 13.9/0.2mm'}

Upvotes: 1

Cyrbil
Cyrbil

Reputation: 6478

Use items() to iterate on keys and values.

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

Or the shorter syntax as suggest by Bhargav Rao:

d = {int(k),v for k,v in d.items()}

Finally as suggested by Manjit Kumar, if your dictionnary does not contains only integer keys:

d = {'not an int': 'test', '123': '456'}
new_d = {}
for k,v in d.items():
    try:
        new_d[int(k)] = v
    except ValueError:
        new_d[k] = v
# new_d = {123: '456', 'not an int': 'test'}

Upvotes: 4

pkacprzak
pkacprzak

Reputation: 5629

Try creating a new dictionary like that:

>>> d = {u'71': u' 12.3/0.2mm', u'70': u' 12.1/0.2mm', u'79': u' 13.9/0.2mm', u'78': u' 13.7/0.2mm'}
>>> 
>>> {int(k): v for k, v in d.items()}
{71: u' 12.3/0.2mm', 70: u' 12.1/0.2mm', 78: u' 13.7/0.2mm', 79: u' 13.9/0.2mm'}

Upvotes: 3

Miguel Jiménez
Miguel Jiménez

Reputation: 514

Try with this:

for key in one_dictionary:
   #Do what you want with int(key)

Upvotes: 0

Related Questions