0
Q:

defaultdict in python

# Defaultdict is a useful way of populating a dictionary without having
# to check if the key already exists in the dictionary

# Basic syntax:
from collections import defaultdict
your_dict = defaultdict(data_type)
# Where:
#	- data_type is the default empty data type that gets created if a
#		key is passed to the dictionary that hasn't already been added

# Exmple usage 1:
your_dict = defaultdict(list) # Set default data type = list
your_dict["a"] = 1
your_dict["b"] = 2
your_dict["c"].append(3) # In a normal dict this would return KeyError
your_dict
--> {'a': 1, 'b': 2, 'c': [3]} # 3 added with default data type = list

# Exmple usage 2:
your_dict = defaultdict(set) # Set default data type = set
your_dict["a"] = 1
your_dict["b"] = 2
your_dict["c"].add(3)
your_dict
--> {'a': 1, 'b': 2, 'c': {3}}

# Exmple usage 2:
your_dict = defaultdict(float) # Set default data type = float
your_dict["a"] = 1
your_dict["b"] = 2
your_dict["c"]
your_dict
--> {'a': 1, 'b': 2, 'c': 0.0} # Calling a key that isn't in the 
#	dictionary results in the addition of that key populated with the
#	default data type
1
>>> from collections import defaultdict
>>> ice_cream = defaultdict(lambda: 'Vanilla')
>>>
>>> ice_cream = defaultdict(lambda: 'Vanilla')
>>> ice_cream['Sarah'] = 'Chunky Monkey'
>>> ice_cream['Abdul'] = 'Butter Pecan'
>>> print ice_cream['Sarah']
Chunky Monkey
>>> print ice_cream['Joe']
Vanilla
>>>
2
d = defaultdict(lambda:1)
1
# 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"]) 
print(d["b"]) 
print(d["c"]) 
1
# Python program to demonstrate 
# defaultdict 
   
   
from collections import defaultdict 
   
   
# Defining the dict 
d = defaultdict(int) 
   
L = [1, 2, 3, 4, 2, 4, 1, 2] 
   
# Iterate through the list 
# for keeping the count 
for i in L: 
       
    # The default value is 0 
    # so there is no need to  
    # enter the key first 
    d[i] += 1
       
print(d) 
0
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
0
>>> from collections import defaultdict
>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
>>> food_count = defaultdict(int) # default value of int is 0
>>> for food in food_list:
...     food_count[food] += 1 # increment element's value by 1
...
defaul
0
# Python program to demonstrate 
# dictionary 
  
  
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}  
print("Dictionary:")  
print(Dict) 
print(Dict[1]) 
  
# Uncommenting this print(Dict[4]) 
# will raise a KeyError as the 
# 4 is not present in the dictionary 
-1

New to Communities?

Join the community