Skip to main content
 首页 » 编程设计

python之生成字典时出现 KeyErrors

2025年05月04日17jirigala

下面是尝试生成dict的dict列表

data = [ 
  {'date': datetime.date(2011, 8, 14), 'name': u'ab', 'total': 8}, 
  {'date': datetime.date(2011, 8, 15), 'name': u'ab', 'total': 8},  
  {'date': datetime.date(2011, 8, 16), 'name': u'ab', 'total': 8},  
  {'date': datetime.date(2011, 8, 17), 'name': u'ab', 'total': 8},  
  {'date': datetime.date(2011, 8, 18), 'name': u'ab', 'total': 8}, 
  {'date': datetime.date(2011, 8, 19), 'name': u'ab', 'total': 8},  
  {'date': datetime.date(2011, 8, 20), 'name': u'ab', 'total': 8},  
  {'date': datetime.date(2011, 8, 21), 'name': u'ab', 'total': 8}, 
  {'date': datetime.date(2011, 8, 18), 'name': u'aj', 'total': 0}, 
  {'date': datetime.date(2011, 8, 14), 'name': u'ap', 'total': 8},  
  {'date': datetime.date(2011, 8, 15), 'name': u'ap', 'total': 8}, 
  {'date': datetime.date(2011, 8, 16), 'name': u'ap', 'total': 8}, 
  {'date': datetime.date(2011, 8, 17), 'name': u'ap', 'total': 8}, 
  {'name': u'ab', 'l_total': 8, 'type': u'UP'},  
  {'name': u'ab', 'l_total': 8, 'type': u'PL'}, 
  {'name': u'fk', 'l_total': 29, 'type': u''}, 
  {'name': u'jw', 'l_total': 1, 'type': u'PD'},  
  {'name': u'uk', 'l_total': 16, 'type': u'UP'},  
  {'name': u'sk', 'l_total': 24, 'type': u'PL'}, 
  {'name': u'ss', 'l_total': 8, 'type': u'PL'}, 
  {'name': u'sst', 'l_total': 8, 'type': u'PL'}] 
 
 
 
results = collections.defaultdict(dict) 
 
for fetch in data: 
        user = fetch['name'] 
        hrs = fetch['total'] 
        row = results[user] 
        new_y = fetch['type'] 
        row['new_y'] = fetch['l_total'] 
        row['user'] = user 
        dt_string = str(fetch['date']) 
        if dt_string in fetch and row[dt_string] != hr: 
          raise Exception, "Contradiction: '%s' on '%s'" % (user, dt_string) 
        row[dt_string] = hrs 
        row.setdefault('Total', 0) 
        row['Total'] += hrs 

同时生成以下输出

{u'ap': {'Total': 32, 'user': u'ap', '2011-08-17': 8,  
         '2011-08-16': 8, '2011-08-15': 8, '2011-08-14': 8, 
         'up': 8, 'PL':8}) 

获取 key 错误,非常感谢任何帮助

注意 :在这里您可以找到两种类型的字典,一种是 {'date': datetime.date(2011, 8, 14), 'name': u'ab', 'total': 8 },还有一个是{'name': u'ab', 'total': 8, 'type': u'UP'},.两者之间的区别是关键。在第一个字典中,您会找到 date key 和另一个字典 type key

请您参考如下方法:

为什么不应该你得到一个 KeyError?您要从 data 的第一行中获取与 type 关联的值,但没有这样的键。

编辑:

@agf 说这没有用,所以让我再试一次。

第一行data是

{'date': datetime.date(2011, 8, 14), 'name': u'ab', 'total': 8} 

在循环中 fetch(顺便说一句,变量应该以名词命名,而不是动词;函数名称是动词)设置为第一行并执行以下行:

new_y = fetch['type'] 

嗯,那条线不能成功。 fetch 中没有 type 的条目,因此,如您所见,Python 抛出 KeyError。更改数据以便有这样的条目或更改代码以使其不需要它。