[Tutor] right way of modifying values of a dictonary
Manprit Singh
manpritsinghece at gmail.com
Thu Oct 21 03:40:23 EDT 2021
Dear sir ,
Take a dict as given below:
dicx = {"A": 23, "J": 38, "L": 29, "R": 26}
Now if i have to change the values in the existing dict( 1 in place of odd
values and 0 in place of even values)
What will be the best way of the two:
1) First way :
>>> dicx = {"A": 23, "J": 38, "L": 29, "R": 26}
>>> dicx.update((key, val%2) for key, val in dicx.items())
>>> dicx
{'A': 1, 'J': 0, 'L': 1, 'R': 0}
2) Second way:
>>> dicx = {"A": 23, "J": 38, "L": 29, "R": 26}
>>> for key, val in dicx.items():
dicx[key] = val%2
>>> dicx
{'A': 1, 'J': 0, 'L': 1, 'R': 0}
in the second way i am iterating over dicx,items() that doesn't seems fine
to me.
3) Third way:
>>> dicx = {"A": 23, "J": 38, "L": 29, "R": 26}
>>> for key in dicx.keys():
dicx[key] = dicx[key]%2
>>> dicx
{'A': 1, 'J': 0, 'L': 1, 'R': 0}
Are 2nd and 3rd way are correct ways to do it ?
Regards
Manprit Singh
Need your guidance.
Regards
Manprit Singh
More information about the Tutor
mailing list