[Python] How to initialize dictionary by get method
Introduction
Here, let me introduce one way to initialize a dictionary variabe in python, which is made by using get() method. A dictionary has a data type of {key: value}. When you want to count the occurrence of each key in a given list, then firs the all values need to be set to zero.
The get() method for dictionary is defined as follow
dict.get(key, default = None)
where key is the key variable of dictionary, whose value will be assigned as a default if the default is given, otherwise be assigned as a preassigned value. The below example shows this implementation.
Examples of get() method
dict = {'Name': 'Zabra', 'Age': 7}
print ("Value : %s" % dict.get('Age'))
>> dict['Age'] = 7 because it default is not given
print ("Value : %s" % dict.get('Education', "Never"))
>> dict['Education'] = Never
Initialize dictionary by get() method
The below code initialize my_dict with zeros for all keys.
nums = [1,2,3,1,1,3] # given list
my_dict={} # declare a dictionary
for n in nums:
my_dict[n] = my_dict.get(n, 0) # default 0 will be assigned to all values
print(my_dict)
We can count the occurrence of each keys while initializing, which is shown in the following code. The only difference from the above code is the addition of +1 at the end of get(n,0) method.
nums = [1,2,3,1,1,3]
my_dict={}
for n in nums:
my_dict[n] = my_dict.get(n, 0)+1
print(my_dict)
# output
>> my_dict = {1: 3, 2: 1, 3: 2}
The output is obtained as expected.