+ 1
What is use of "get" in dictionaries in Python
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
+ 4
Here's an example of get()
https://code.sololearn.com/c3764yI7Ri8X/?ref=app
+ 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')
+ 1
HonFu So it's like indexing but for dictionaries!?