I have the following dictionary.
dct = {'hello':1.9,'ciao':1.5,'yes':-2,'no':-3}
I would like to replace positive values with 1 and negative values with -1.
I tried many codes, one of which below:
np.where(dct.values() > 0, 1, 0)
np.where(dct.values() > 0, -1, 0)
However, it did not manage to make it work. How can I do it?
Thanks!
You could achieve this with a dict comprehension (not sure how you want to handle exactly equal to zero, if you expect that to occur)
>>> d = {'hello': 1.9,'ciao': 1.5,'yes': -2,'no': -3}
>>> {k: 1 if v > 0 else -1 for k, v in d.items()}
{'hello': 1, 'ciao': 1, 'yes': -1, 'no': -1}
The conditional expression
1 if v >= 0 else -1
is maybe the most intelligible, but there are some shorter options :-)
(v >= 0) - (v < 0)
2 * (v >= 0) - 1
(1, -1)[v < 0]
from math import copysign as cs
cs(1, v) # if you are ok with floats
just to list a few. Of course, all of them can plugged into the dict comprehension:
dct = {k: cs(1, v) for k, v in dct.items()}
This can also be done using math.copysign
although is probably a bit overboard for a small application otherwise I would use what others have posted.
>>> from math import copysign
>>> {k: int(copysign(1, v)) for k, v in dct.items()}
{'hello': 1, 'ciao': 1, 'yes': -1, 'no': -1}
Here is your answer:
{k: 1 if v > 0 else -1 for k, v in dict.items()}
Do not use dict as variable name, by the way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.