Python's defaultdict

Source: Internet
Author: User

Defaultdict is a subclass of Dict, accepting a factory function as a parameter, and when accessing a key that does not exist in Defaultdict, the return value of the factory function is used as the default value.

class defaultdict (dict):     """     defaultdict (default_factory[, ...])-Dict with default factory the        default factory is called without AR Guments to produce    a new value when a key was not present, in __getitem__ only.    A defaultdict compares equal to a dict with the same items.    All remaining arguments is treated the same as if they were passed    to the Dict constructor, including keyword Argume NTS.     """

Test code

Complete code: https://github.com/blackmatrix7/python-learning/blob/master/other/defaultdict.py

__author__='Blackmatrix'defFactory_func ():return 'default_factory'test_defaultdict=defaultdict (Factory_func)if __name__=='__main__':    " "When a key is present, it returns the value corresponding to the key, which is no different from the normal dict." "test_defaultdict['a'] ='233333'    Print(test_defaultdict['a'])    " "The return value of the factory function is automatically used as the default value when accessing a nonexistent key" "    Print(test_defaultdict['b'])    Print(test_defaultdict['C'])

Run results

233333default_factorydefault_factory

If Defaultdict does not pass in the factory function when it is created, it throws keyerror when it accesses a nonexistent key.

 from Import  = defaultdict ()print(test_defaultdict2['x')  #  keyerror: ' x '

Python's defaultdict

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.