Skip to main content
added 1 character in body
Source Link
Asclepius
  • 64.6k
  • 20
  • 188
  • 164

I usually use a defaultdict for situations like this. You supply a factory method that takes no arguments and creates a value when it sees a new key. It's more useful when you want to return something like an empty list on new keys (see the examples).

from collections import defaultdict d = defaultdict(lambda : None) print d['new_key'] #prints # prints 'None' 

I usually use a defaultdict for situations like this. You supply a factory method that takes no arguments and creates a value when it sees a new key. It's more useful when you want to return something like an empty list on new keys (see the examples).

from collections import defaultdict d = defaultdict(lambda : None) print d['new_key'] #prints 'None' 

I usually use a defaultdict for situations like this. You supply a factory method that takes no arguments and creates a value when it sees a new key. It's more useful when you want to return something like an empty list on new keys (see the examples).

from collections import defaultdict d = defaultdict(lambda: None) print d['new_key']  # prints 'None' 
Source Link
job
  • 9.4k
  • 7
  • 44
  • 50

I usually use a defaultdict for situations like this. You supply a factory method that takes no arguments and creates a value when it sees a new key. It's more useful when you want to return something like an empty list on new keys (see the examples).

from collections import defaultdict d = defaultdict(lambda : None) print d['new_key'] #prints 'None'