Post

Python Programming
Python Programming@PythonPr·
Python Question / Quiz; What is the output of the following Python code, and why? Comment your answers below!
Python Programming tweet media
English
24
12
137
11.4K
Coding Computing Coach
Coding Computing Coach@CodingComputing·
@PythonPr Answer: B Solution: my_dict is a dict with 3 keys: 'a', 'b', and 'c'. Let's figure out what's: my_dict.get('d', 4) The `get` dictionary method is used to get value for a key from the dictionary. Similar to [] notation. But there is a difference. If you try to access +
English
1
0
2
452
Coding Computing Coach
Coding Computing Coach@CodingComputing·
@PythonPr a non-existent key with [], you'll get an error. So, something like my_dict['d'] will give a KeyError, because 'd' isn't a key in my_dict. But sometimes, if a key isn't in the dictionary, we don't want an error. That's when `get` comes in to help... +
English
1
0
0
38
Coding Computing Coach
Coding Computing Coach@CodingComputing·
@PythonPr my_dict.get('d', 4) tells python to: - check if 'd' is a key of my_dict - if yes, then access the value for 'd' in my_dict - if no, then give the value 4 (the 2nd argument) So, there is no error with `get`. Instead, a "not-found" default value is specified as 2nd argument. +
English
1
0
0
54
Поделиться