Pythonic Ways to Use Dictionaries
Python dictionaries are a useful part of the language. In addition to having the ability to store keys and values, you can also use dictionary methods to manipulate those values, and you can use dictionaries to write more concise code. Use get() and setdefault() with Dictionaries Trying to access a dictionary key that doesn’t exist will result in a KeyError error, so programmers often will write unpythonic code to avoid the situation like this: >>> # Unpythonic Example >>> workDetails = {} >>> if 'hours' in spam: ... hoursWorked = workDetails['hours'] ... else: ... hoursWorked = 0 # Default to 0 if the 'hours' key doesn't exist. ... >>> hoursWorked 0 This pattern happens so often that dictionaries have a get() method that allows you specify a default value to return when a key doesn’t exist in the dictionary. The following code is equivalent to the previous example, but is py...