Today, I came across the dict
method get
which, given a key in the dictionary, returns the associated value.
For what purpose is this funct
For what purpose is this function useful?
One particular usage is counting with a dictionary. Let's assume you want to count the number of occurrences of each element in a given list. The common way to do so is to make a dictionary where keys are elements and values are the number of occurrences.
fruits = ['apple', 'banana', 'peach', 'apple', 'pear']
d = {}
for fruit in fruits:
if fruit not in d:
d[fruit] = 0
d[fruit] += 1
Using the .get()
method, you can make this code more compact and clear:
for fruit in fruits:
d[fruit] = d.get(fruit, 0) + 1