How does collections.defaultdict work?

前端 未结 15 2214
离开以前
离开以前 2020-11-22 12:50

I\'ve read the examples in python docs, but still can\'t figure out what this method means. Can somebody help? Here are two examples from the python docs

>         


        
15条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 13:01

    Dictionaries are a convenient way to store data for later retrieval by name (key). Keys must be unique, immutable objects, and are typically strings. The values in a dictionary can be anything. For many applications, the values are simple types such as integers and strings.

    It gets more interesting when the values in a dictionary are collections (lists, dicts, etc.) In this case, the value (an empty list or dict) must be initialized the first time a given key is used. While this is relatively easy to do manually, the defaultdict type automates and simplifies these kinds of operations. A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key.

    A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.

    from collections import defaultdict
    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
    

    Here is another example on How using defaultdict, we can reduce complexity

    from collections import defaultdict
    # Time complexity O(n^2)
    def delete_nth_naive(array, n):
        ans = []
        for num in array:
            if ans.count(num) < n:
                ans.append(num)
        return ans
    
    # Time Complexity O(n), using hash tables.
    def delete_nth(array,n):
        result = []
        counts = defaultdict(int)
    
        for i in array:
            if counts[i] < n:
                result.append(i)
                counts[i] += 1
        return result
    
    
    x = [1,2,3,1,2,1,2,3]
    print(delete_nth(x, n=2))
    print(delete_nth_naive(x, n=2))
    

    In conclusion, whenever you need a dictionary, and each element’s value should start with a default value, use a defaultdict.

提交回复
热议问题