+ 1

What is use of "get" in dictionaries in Python

12th May 2019, 7:02 AM
Harsh Tyagi
Harsh Tyagi - avatar
4 ответов
+ 7
You can specify what you want instead if the item you ask for is not inside the dict, so you won't get an error. d = {'a': 1, 'b': 2} print(d.get('c', 'not in there')) Output: not in there
12th May 2019, 7:15 AM
HonFu
HonFu - avatar
13th May 2019, 4:39 AM
David Ashton
David Ashton - avatar
+ 3
No, with indexing, if you choose a key that's not contained, you'll get an error. print(d['c']) --> error. So for indexing you have to be sure that what you're asking for is actually there. get (in this example) is like writing: if 'c' in d: print(d['c']) else: print('not in there')
12th May 2019, 7:27 AM
HonFu
HonFu - avatar
+ 1
HonFu So it's like indexing but for dictionaries!?
12th May 2019, 7:24 AM
Harsh Tyagi
Harsh Tyagi - avatar