Skip to content

Instantly share code, notes, and snippets.

@mwrites
Last active October 12, 2021 18:35
Show Gist options
  • Save mwrites/e776413ab44acd50275d77281b8eeed4 to your computer and use it in GitHub Desktop.
Save mwrites/e776413ab44acd50275d77281b8eeed4 to your computer and use it in GitHub Desktop.
Python - Dictionary With Default Values
hashmap = {
'vegetables': ['Carrot', 'Tomato'],
'fruits': ['Apple', 'Banana']
}
# **************
# Default Values
# **************
hashmap['missing_key'] # KeyError
hashmap.get('missing_key') # None
hashmap.get('missing_key', 'default value') # default value
# Get value or default value + append
# all of these are wrongs
hashmap['meat'].append('chicken') # Same case as line 10
hashmap.get('meat').append('chicken') # Same case as line 11
hashmap.get('meat', []).append('chicken') # Does not mutate hashmap, use setdefault instead
# This works
hashmap.setdefault('meat', []).append('chicken') # {.. 'meat': ['chicken']}
# **************
# With default dict
# **************
hashmap_default = defaultdict(list)
hashmap_default['vegetables'] = ['Carrot', 'Tomato']
hashmap_default['fruits'] = ['Apple', 'Banana']
hashmap['missing_key'] # [] as it is the default we specified when doing defaultdict(list)
hashmap.get('missing_key') # Still None!
hashmap['meat'].append('chicken') # {.. 'meat': ['chicken']}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment