xxxxxxxxxx
from collections import defaultdict
d_int = defaultdict(int)
d_list = defaultdict(list)
def foo():
return 'default value'
d_foo = defaultdict(foo)
>>> d_int
defaultdict(<type 'int'>, {})
>>> d_list
defaultdict(<type 'list'>, {})
>>> d_foo
defaultdict(<function foo at 0x7f34a0a69578>, {})
xxxxxxxxxx
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.setdefault('Age', None)
print "Value : %s" % dict.setdefault('Sex', None)
>>Value : 7
>>Value : None
xxxxxxxxxx
Alternative to Default Dict (int):
dictionary[i] = 1 + dictionary.get(i, 0)
xxxxxxxxxx
# set default values for all keys
d = collections.defaultdict(lambda:1)
# set default value for a key if not exist - will not modify dictionary
value = d.get(key,default_value)
# if key is in the dictionary: return value
# else: insert the default value as well as return it
dict_trie.setdefault(char,{})
xxxxxxxxxx
from collections import defaultdict
# Declare a defaultdict with a default value of 'Unknown'
data = defaultdict(lambda: 'Unknown')
# Assign values to keys
data['name'] = 'John'
data['age'] = 30
# Accessing keys that do not exist returns the default value
print(data['name']) # Output: John
print(data['city']) # Output: Unknown
xxxxxxxxxx
>>> from collections import defaultdict
>>> d = {'foo': 123, 'bar': 456}
>>> d['baz']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'baz'
>>> d = defaultdict(lambda: -1, d)
>>> d['baz']
-1
xxxxxxxxxx
# Python program to demonstrate
# defaultdict
from collections import defaultdict
# Function to return a default
# values for keys that is not
# present
def def_value():
return "Not Present"
# Defining the dict
d = defaultdict(def_value)
d["a"] = 1
d["b"] = 2
print(d["a"]) # 1
print(d["b"]) # 2
print(d["c"]) # Not Present