I have the following Python code to iterate over a nested dictionary and grab a value from the second child:
ret = some_dict
for item, val in ret.items():
for item2, val2 in val.items():
print val2['result']
When I test this in IPython or the interactive Python interpreter, the code works fine, and prints the value of val2['result'] for each item in the dictionary. However, when I use this block of code in a Python program I get the following error when trying to print val2['result']:
TypeError: string indices must be integers, not str
If I print json.dumps(val2, indent=2), I can see that the dictionary is formed correctly. Attempting to use dict() to cast val2 to a dictionary in the script also fails with the following error:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
I'm not entirely sure what I'm doing wrong at this point, since the code works in the interactive interpreter. I am using Python 2.7.6, and the use case is iterating over a dictionary returned by the Saltstack Python client.
Believe the message: it is telling you that val2
is a string when you think it is a dict. This is almost certainly due to your JSON data not being structured as you think it is.