+ 1

What does 'get' method provides any easiness in dictionary?

Get method gives NONE if the key is not in the dictionary. How can this be used in any code? What is the advantage?

11th Aug 2017, 12:53 AM
Mehmet Fatih YILDIRIM
Mehmet Fatih YILDIRIM - avatar
1 Respuesta
+ 8
Hello; "get" a method in the built-in class 'dict' You're asking what we'll profit from using it. Well, for me it's a quite usefull method. ---- The easiest way to access the value of a key from a dict is: dict[key] ( e.g. r = colors["red"] ) So why using? dict.get(key) The issue in using the former ( dict[key] ) is that it raises a KeyError if dict doesn't have the requested key. There are many cases when we just want to access the value of the key (if exists) and really don't want to have an error statement. So we use something like this: ( replace 'key' and 'dict' with your desired key and dict ) if key in dict.keys(): k = dict[key] else: k = None Guess what! We can re-write that in one line: ######## k = dict.get(key, None) ######## None is optional. Hope I Helped ⭐
11th Aug 2017, 2:01 AM
MizoPro
MizoPro - avatar