How to pull an item from a Python dictionary without triggering a KeyError? In Perl, I would do:
$x = $hash{blah} || 'default'
What is equivalent Python?
Use the method get(key, default):
get(key, default)
>>> dict().get("blah", "default") 'default'
If you are going to do this a lot, it is better to use collections.defaultdict :
import collections # Define a little "factory" function that just builds the default value when called. def get_default_value(): return 'default' # Create a defaultdict, specifying the factory that builds its default value dict = collections.defaultdict(get_default_value) # Now we can look up things without checking, and get 'default' if the key is unknown x = dict['blah']
x = hash['blah'] if 'blah' in hash else 'default'
x = hash.has_key('blah') and hash['blah'] or 'default'
Source: https://habr.com/ru/post/1704735/More articles:SharePoint Permission on Mac - sharepointC # and .NET 3.5 - How to start a process using different credentials with a hidden window and the ability to capture standard output and output code? - c #Redirecting from the doView method in the portlet - javaHow to apply a patch using svn export? - svnИздевательские методы, используемые в статических методах - phpSVN fork and "IIS URL is already mapped to another location" - svnJavaScript для PDF: что означает токен, используемый getPageNthWord()? - javascriptConcurrency последствия использования EAFP/LBYL - pythonWhich PHP / MySQL book would be good as a tutorial? - phphelp with complex joins in Django ORM - pythonAll Articles