Iterate over a dict or list in Python
- by Chris Dutrow
Just wrote some nasty code that iterates over a dict or a list in Python. I have a feeling this was not the best way to go about it.
The problem is that in order to iterate over a dict, this is the convention:
for key in dict_object:
dict_object[key] = 1
But modifying the object properties by key does not work if the same thing is done on a list:
# Throws an error because the value of key is the property value, not
# the list index:
for key in list_object:
list_object[key] = 1
The way I solved this problem was to write this nasty code:
if isinstance(obj, dict):
for key in obj:
do_loop_contents(obj, key)
elif isinstance(obj, list):
for i in xrange(0, len(obj)):
do_loop_contents(obj, i)
def do_loop_contents(obj, key):
obj[key] = 1
Is there a better way to do this?
Thanks!