[Tutor] Update values in python dicts
Manprit Singh
manpritsinghece at gmail.com
Mon May 3 12:42:02 EDT 2021
Dear sir ,
consider a dict as given below :
dic = {"A": 1, "B": 8, "H": 5, "L": 4, "K": 7}
I have to update those key value pairs, where the values are odd numbers,
all these values are to be incremented by 2 so after the update the same
dict will become :
dic = {'A': 3, 'B': 8, 'H': 7, 'L': 4, 'K': 9}
The way i am doing this is by executing the below written code:
dic = {"A": 1, "B": 8, "H": 5, "L": 4, "K": 7}
dic.update((x, y+2) for x, y in dic.items() if y%2 != 0)
print(dic)
gives the right answer.
Here a generator expression and update method is used. Instead of doing
this, the task can be done with a single for loop as below :
dic = {"A": 1, "B": 8, "H": 5, "L": 4, "K": 7}
for key, val in dic.items():
if val%2 != 0:
dic[key] = val + 2
print(dic)
which will give the desired result.
What should be preferred in this particular case . Kindly guide
Regards
Manprit Singh
More information about the Tutor
mailing list