Simd
Simd

Reputation: 21333

How to convert all suitable values to int

I have a large dictionary of about 100 million key/value pairs.

I would like to convert all the values which can easily be converted to ints.

For example if I start with:

b = {'one': '001', 'two': 2, 'three': 'three'}

I would like the result to be

b2 = {'one': 1, 'two': 2, 'three': 'three'}

If I simply iterate over b and cast all the values to int I get an error when it gets to 'three'.

How can one do this?

Upvotes: 0

Views: 70

Answers (3)

The6thSense
The6thSense

Reputation: 8335

You need an external function to convert string to int here I have used int_conversion and have used dict comprehension to create the second dictionary

Code:

dic = {'one': '001', 'two': 2, 'three': 'three'}

def int_conversion(value):
    try:
        return int(value)
    except Exception:
        return value   
b2={key:int_conversion(value) for key,value in dic.iteritems()}
print b2

Output:

{'one': 1, 'three': 'three', 'two': 2}

Upvotes: 2

AChampion
AChampion

Reputation: 30268

Though perhaps a little unpythonic you could test to see if is a digit before converting:

b2 = {k: int(v) if isinstance(v, str) and v.isdigit() else v for k, v in b.items()}

Upvotes: 1

Anand S Kumar
Anand S Kumar

Reputation: 90979

You can use try/except to catch the ValueError thrown by int() when three is passed in. Example -

b2 = {}
for k,v in b.items():
    try:
        b2[k] = int(v)
    except ValueError:
        b2[k] = v

You should note, this would also truncate floats to integer , but I am guessing that is expected behavior.


Demo -

>>> b = {'one': '001', 'two': 2, 'three': 'three'}
>>> b2 = {}
>>> for k,v in b.items():
...     try:
...         b2[k] = int(v)
...     except ValueError:
...         b2[k] = v
...
>>> b2
{'one': 1, 'two': 2, 'three': 'three'}

Upvotes: 3

Related Questions