【问题标题】:Python3.6 4-level dictionaries giving KeyError [duplicate]Python3.6 4级字典给出KeyError [重复]
【发布时间】:2018-06-04 21:49:33
【问题描述】:

我想在 python 中处理嵌套字典以存储唯一数据。但是,我不知道正确的方法是什么。我尝试了以下方法:

my_dict = collections.defaultdict(dict)
my_dict[id1][id2][id2][id4] = value

但它会导致 KeyError。 这样做的正确方法是什么?

【问题讨论】:

    标签: python python-3.x dictionary defaultdict


    【解决方案1】:

    一种简单的方法

    mainDict = {}
    mainDict['id1']={}
    mainDict['id1']['id2'] ={}
    mainDict['id1']['id2']['id3'] = 'actualVal'
    
    print(mainDict)
    
    
    # short explanation of defaultdict
    
    import collections
    
    # when a add some key to the mainDict, mainDict will assgin 
    # an empty dictionary as the value
    
    mainDict = collections.defaultdict(dict)
    
    # adding only key, The value will be auto assign.
    mainDict['key1']
    
    print(mainDict)
    # defaultdict(<class 'dict'>, {'key1': {}})
    
    # here adding the key 'key2' but we are assining value of 2
    mainDict['key2'] = 2 
    print(mainDict)
    
    #defaultdict(<class 'dict'>, {'key1': {}, 'key2': 2})
    
    
    # here we are adding a key 'key3' into the mainDict
    # mainDict will assign an empty dict as the value.
    # we are adding the key 'inner_key' into that empty dictionary
    # and the value as 10
    
    mainDict['key3']['inner_key'] = 10
    print(mainDict)
    
    #defaultdict(<class 'dict'>, {'key1': {}, 'key2': 2, 'key3': {'inner_key': 10}})
    

    【讨论】:

      【解决方案2】:

      如果你想创建一个嵌套的 defaultdict 到尽可能多的深度,那么你想将 defaultdict 的默认类型设置为返回具有相同类型的 defaultdict 的函数。所以看起来有点递归。

      from collections import defaultdict
      
      def nest_defaultdict():
          return defaultdict(nest_defaultdict)
      
      d = defaultdict(nest_defaultdict)
      d[1][2][3] = 'some value'
      print(d)
      print(d[1][2][3])
      
      # Or with lambda
      f = lambda: defaultdict(f)
      d = defaultdict(f)
      

      如果您不需要任何任意深度,那么Fuji Clado's 答案将演示设置嵌套字典并对其进行访问。

      【讨论】:

        猜你喜欢
        • 2014-04-24
        • 2022-11-20
        • 2017-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多