zoukankan      html  css  js  c++  java
  • 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


     
  • 相关阅读:
    名字空间,L,E, G , B 作用域, 内置电池
    lambda表达式
    表达式与声明的区别。
    jupyter book的使用
    centos7一键安装cacti_1.2.16版本
    docker修改阿里云镜像加速器
    centos单网卡多ip,被动模式
    centos同步时间
    centos7.x制作bond
    centos 6.X制作bond
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13724496.html
Copyright © 2011-2022 走看看