2016-04-06 42 views
-2

我已经用python创建了一个用于遍历多级字典的函数,并执行需要四个参数的第二个函数ssocr:coord,background,foreground,type(它们是我的键的值)。 这是我从json文件中提取的字典。Iteritems在Python中的字典

document json

`

def parse_image(self, d): 
    bg = d['background'] 
    fg = d['foreground'] 
    results = {} 
    for k, v in d['boxes'].iteritems(): 
     if 'foreground' in d['boxes']: 
      myfg = d['boxes']['foreground'] 
     else: 
      myfg = fg 
     if k != 'players_home' and k != 'players_opponent': 
      results[k] = MyAgonism.ssocr(v['coord'], bg, myfg, v['type']) 

    results['players_home'] = {} 
    for k, v in d['boxes']['players_home'].iteritems(): 
     if 'foreground' in d['boxes']['players_home']: 
      myfg = d['boxes']['players_home']['foreground'] 
     else: 
      myfg = fg 
     if k != 'background' and 'foreground': 
      for k2, v2 in d['boxes']['players_home'][k].iteritems(): 
       if k2 != 'fouls': 
        results['players_home'][k] = MyAgonism.ssocr(v2['coord'], bg, myfg, v2['type']) 
    return results 

我在第二前景检查错误持续iteritems,我的钥匙数覆盖的关键得分

+3

这个异常说:你在字符串上调用'iteritems',而不是字典。 –

+0

如果你使用python 3.x,你应该使用'dic.items'而不是'dic.iteritems' – Arman

+0

@Arman python 2;它说'unicode' –

回答

1

你的问题是在这里:

if k != 'background' and 'foreground': 
    # do something 

哪一个没有做检查你认为它是这样做。你想有效

if (k != "background") and ('foreground'): 
    # do something 

其结果始终为True(因为一个非空字符串被认为是“truthy”)。

只需更改该行:

if k not in ('background', 'foreground'): 
    # do stuff 

或做你做进一步向上的函数(if k != 'players_home' and k != 'players_opponent':)以同样的方式,你应该在企业。

+0

很尴尬的错误,浪费了半个小时,没有注意到它。谢谢。 – Eldar88

+0

@ Eldar88不需要尴尬......发生在我们所有人身上。也就是说,我强烈建议学习使用pdb(或者更好的ipdb)在代码中设置一个断点,然后逐行逐行找到您的问题。学习一项能够在未来多次支付回报的技能是一项很小的投资。 – randlet

+0

我仍然发现重写密钥的问题,我想,在上一个周期 – Eldar88