• python中defaultdict


    Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dict class that returns a dictionary-like object. The functionality of both dictionaries and defualtdict are almost same except for the fact that defualtdict never raises a KeyError. It provides a default value for the key that does not exists.

    Syntax: defaultdict(default_factory)

    Parameters:

    • default_factory: A function returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError.

    Example:

     
    # Python program to demonstrate
    # defaultdict
      
      
    from collections import defaultdict
      
      
    # Function to return a default
    # values for keys that is not
    # present
    def def_value():
        return "Not Present"
          
    # Defining the dict
    d = defaultdict(def_value)
    d["a"] = 1
    d["b"] = 2
      
    print(d["a"])
    print(d["b"])
    print(d["c"])

    Output:

    1
    2
    Not Present

    Using List as default_factory

    When the list class is passed as the default_factory argument, then a defaultdict is created with the values that are list.

    Example:

     
    # Python program to demonstrate
    # defaultdict
      
      
    from collections import defaultdict
      
      
    # Defining a dict
    d = defaultdict(list)
      
    for i in range(5):
        d[i].append(i)
          
    print("Dictionary with values as list:")
    print(d)

    Output:

    Dictionary with values as list:
    defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})
    

    Using int as default_factory

    When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.

    Example:

     
    # Python program to demonstrate
    # defaultdict
       
       
    from collections import defaultdict
       
       
    # Defining the dict
    d = defaultdict(int)
       
    L = [1, 2, 3, 4, 2, 4, 1, 2]
       
    # Iterate through the list
    # for keeping the count
    for i in L:
           
        # The default value is 0
        # so there is no need to 
        # enter the key first
        d[i] += 1
           
    print(d)

    Output:

    defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})

    这个factory_function可以是list、set、str等等,当key不存在时,返回的是factory_function的默认值,比如list对应[ ],str对应的是空字符串,set对应set( ),int对应0


     
  • 相关阅读:
    对于Python中self的看法
    SpringBoot整合MyBatis-Plus快速开始
    Hive原理--体系结构
    Docker Compose + Traefik v2 快速安装, 自动申请SSL证书 http转https 初次尝试
    记录:更新VS2019后单元测试运行卡住无法运行测试的问题。
    黑帽来源页劫持代码以及如何防范
    OFFICE 2010 每次打开提示安装的问题
    Mssql 查询某记录前后N条
    验证邮箱正则表达式,包含二级域名邮箱,手机号正则表达式支持170号段
    删除TFS上的团队项目
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13724496.html
Copyright © 2020-2023  润新知