0

I have a dictionary like :

a={
   'sig2/Bit 2': ['0', '0', '1'], 
   'sig1/Bit 1': ['1', '0', '1']
  }

I want to convert it like :

a={
   'sig2/Bit 2': [0, 0, 1], 
   'sig1/Bit 1': [1, 0, 1]
  }

Please help me out.

Nilesh
  • 20,521
  • 16
  • 92
  • 148
user3487900
  • 111
  • 1
  • 1
  • 6
  • possible duplicate of [Convert all strings in a list to int](http://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int) – Ashwini Chaudhary Apr 04 '14 at 10:29

7 Answers7

3

I will not provide you with the complete answer but rather guidance on how to do it. Here is an example:

>>> d = ['0', '0', '1']
>>> print [int(i) for i in d]
[0,0,1]

Hopefully that should be enough to guide you to figure this out.
Hint: iterate through the dictionary and do this for each key/value pair. Good Luck

sshashank124
  • 31,495
  • 9
  • 67
  • 76
0
for i in a.keys():
    a[i] = [int(j) for j in a[i]]
Holloway
  • 6,412
  • 1
  • 26
  • 33
0

May be there are better ways, but here is one.

for key in a:
    a[key] = [int(x) for x in a[key]];
Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85
0

Try this out

In [54]: dict([(k, [int(x) for x in v]) for k,v in a.items()])
Out[54]: {'sig1/Bit 1': [1, 0, 1], 'sig2/Bit 2': [0, 0, 1]}
Nilesh
  • 20,521
  • 16
  • 92
  • 148
0
for key, strNumbers in a.iteritems():
  a[key] = [int(n) for n in strNumbers]
rparent
  • 630
  • 7
  • 14
0

You can try this ,

>>> a={
   'sig2/Bit 2': ['0', '0', '1'], 
   'sig1/Bit 1': ['1', '0', '1']
  }

>>> for i in a.keys():
        a[i]=map(int,a[i])

Output:

>>> print a
{'sig2/Bit 2': [0, 0, 1], 'sig1/Bit 1': [1, 0, 1]}
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
0

It is as easy as:

a = {
    'sig2/Bit 2': ['0', '0', '1'], 
    'sig1/Bit 1': ['1', '0', '1']
}

b = dict((x, map(int, y)) for x, y in a.iteritems())

UPDATE

For last line in code above you could use dict comprehension:

b = {x: map(int, y) for x, y in a.iteritems()}
maxbublis
  • 1,273
  • 10
  • 21