Reputation: 472
Suppose that I have dictionary as follows
res = {'a':[10, 20, 3.9, 'NA', 'NA', 2.2]}
I want to multiply the dictionary values with a scalar only where the type is not string.
I've tried multiplying using the following code
res['a'] * 10.2
Expected Output
scalar = 10.2
res = {'a':[102, 204, 39.78, 'NA', 'NA', 22.44]}
Upvotes: 0
Views: 85
Reputation: 13939
You can use isinstance
to detect which are non-strings, and then use ...if...else...
to apply * 10.2
to those elements:
res = {'a':[10, 20, 3.9, 'NA', 'NA', 2.2]}
res['a'] = [x * 10.2 if not isinstance(x, str) else x for x in res['a']]
print(res) # {'a': [102.0, 204.0, 39.779999999999994, 'NA', 'NA', 22.44]}
If you want to "positively" check whether an element is a number, then you can use if isinstance(x, (float, int))
instead.
Upvotes: 3