Why dict.get(key) instead of dict[key]?

后端 未结 10 2487
生来不讨喜
生来不讨喜 2020-11-21 05:51

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

10条回答
  •  不思量自难忘°
    2020-11-21 06:10

    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
    

提交回复
热议问题