How to rewrite $ x = $ hash {blah} || 'default' in Python?

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?

+3
source share
4 answers

Use the method get(key, default):

>>> dict().get("blah", "default")
'default'
+9
source

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']
+7
source
x = hash['blah'] if 'blah' in hash else 'default'
+1
source
x = hash.has_key('blah') and hash['blah'] or 'default'
0
source

Source: https://habr.com/ru/post/1704735/


All Articles