dict-get
Often while using dictionaries in Python, you may run into KeyErrors
. This error is raised when you try to access a key that isn't present in your dictionary. Python gives you some neat ways to handle them.
The dict.get
method will return the value for the key if it exists, and None (or a default value that you specify) if the key doesn't exist. Hence it will never raise a KeyError.
>>> my_dict = {"foo": 1, "bar": 2}
>>> print(my_dict.get("foobar"))
None
Below, 3 is the default value to be returned, because the key doesn't exist-
>>> print(my_dict.get("foobar", 3))
3
Some other methods for handling KeyError
s gracefully are the dict.setdefault
method and collections.defaultdict
(check out the !defaultdict
tag).
range-len
Beginners often iterate over range(len(...))
because they look like Java or C-style loops, but this is almost always a bad practice in Python.
for i in range(len(my_list)):
do_something(my_list[i])
It's much simpler to iterate over the list (or other sequence) directly:
for item in my_list:
do_something(item)
Python has other solutions for cases when the index itself might be needed. To get the element at the same index from two or more lists, use zip. To get both the index and the element at that index, use enumerate.