Skip to content

Instantly share code, notes, and snippets.

@cwalkatron
Created May 20, 2013 18:30
Show Gist options
  • Save cwalkatron/5614225 to your computer and use it in GitHub Desktop.
Save cwalkatron/5614225 to your computer and use it in GitHub Desktop.
defaultdict use
# instead of this
x, y, z = 1, 2, 3
d = {}
if not d.has_key(x):
d[x] = {}
if not d[x].has_key(y):
d[x][y] = []
d[x][y].append(z)
# this
from collections import defaultdict
d = defaultdict(lambda : defaultdict(list))
d[x][y].append(z)
@bitness
Copy link

bitness commented May 20, 2013

x, y, z = 1, 2, 3                                                               
d = {}                                                                          
t = d.setdefault(x, {}).setdefault(y, [])                                       
t[x][y] = z

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment