are python collections useful code example
Example 1: python collections
# Dictionary where key values default to a list:
a = collections.defaultdict(list)
# Dictionary where key values default to 0:
a = collections.defaultdict(int)
# Dictionary where key values default to another dictionary:
a = collections.defaultdict(dict)
'''
Example:
In a regular dictionary, if you did the following:
a = {}
if a['apple'] == 1:
return True
else:
return False
You'd get an error, because 'apple' does not exist in dictionary.
However, if you use collections:
a = collections.defaultdict(int)
if a['apple'] == 1:
return True
else:
return False
This would not give an error, and False would be returned.
Also, the dictionary would now have the key 'apple' with a
default integer value of 0 inside it.
If you used say, collections.defaultdict(list), the default value
would be an empty list instead of 0.
'''
Example 2: python collections
list = [1,2,3,4,1,2,6,7,3,8,1]
Counter(list)