【问题标题】:Overriding a value in a iteritems loop覆盖迭代项循环中的值
【发布时间】:2016-04-06 16:26:15
【问题描述】:

我创建了一个用于遍历多级字典的函数,并执行第二个函数ssocr,它需要四个参数:坐标、背景、前景、类型(它们是我的键的值)。这是我的字典,取自 json 文件。

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 k != 'foreground':
            for k2, v2 in d['boxes']['players_home'][k].iteritems():
                if k2 != 'fouls':
                    results['players_home'][k] = {}
                    results['players_home'][k][k2] = MyAgonism.ssocr(v2['coord'], bg, myfg, v2['type'])

    return results

在最后的迭代中,我只为 name 键获得了正确的值。 score 键没有出现。在我的 results['players_home'] 字典中看起来像 name 覆盖 score

输出:... "player4": {"name": 9}, "player5": {"name": 24} ...

我想要... "player4": {"name": 9, "score": value}, "player5": {"name": 24, "score": value} ...之类的东西

我做错了什么?这是完整的代码以防万一:Full Code

【问题讨论】:

    标签: python json python-2.7 dictionary


    【解决方案1】:

    这可能是/一个问题:

                if k2 != 'fouls':
                    results['players_home'][k] = {}
    

    在您的循环中,每次k2 不是'fouls',您都会创建一个新的空字典并将其存储在results['players_home'] 中。这意味着以前存储在那里的任何条目都不再可访问。

    【讨论】:

    • 将该语句移到循环之外它可以正常工作。谢谢
    猜你喜欢
    • 2016-09-18
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多