[Tutor] right way of modifying values of a dictonary

Alan Gauld alan.gauld at yahoo.co.uk
Thu Oct 21 05:20:47 EDT 2021


On 21/10/2021 08:40, Manprit Singh wrote:

> 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}
> 
> 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}

Personally I'd probably use the third way as it is most explicit.
But the best, and most Pythonic, way is probably the first way.

> Are 2nd and 3rd way are correct ways to do it ?

Correct in the sense they give the correct result and are
easy to read and maintain. But they are probably not optimal.

-- 
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