[Tutor] Update values in python dicts
Alan Gauld
alan.gauld at yahoo.co.uk
Mon May 3 13:15:28 EDT 2021
On 03/05/2021 17:42, Manprit Singh wrote:
> 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)
> 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
> What should be preferred in this particular case . Kindly guide
If you rename the vars in the first to match the second:
dic.update((key, val+2) for key, val in dic.items() if val%2)
Then there is very little to separate them. The explicit
loop is maybe slightly easier to read for a beginner
but probably slower to execute.
To make the update even more readable I'd probably opt
for a dict comprehension update argument:
dic.update({key:val+2 for key, val in dic.items() if val%2})
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list