Eldar88 Eldar88 - 6 months ago 13
JSON Question

Overriding a value in a iteritems loop

I've created a function for iterating through a multiple level dictionary, and execute a second function

ssocr
that needs four arguments: coord, background, foreground, type (they are the value of my keys). This is my dictionary which is taken from a json file.

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


In the last iteritems I get the correct value just for the
name
key. The
score
key doesn't appear. It looks like
name
override
score
in my
results['players_home']
dictionary

output:
... "player4": {"name": 9}, "player5": {"name": 24} ...


I would like something like
... "player4": {"name": 9, "score": value}, "player5": {"name": 24, "score": value} ...


What am I doing wrong? Here is the full code just in case: Full Code

dsh dsh
Answer

This might be the/a problem:

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

In your loop, each time that k2 is not 'fouls', you create a new empty dict and store that in results['players_home']. That means that any entry previously stored there is no longer accessible.