Iterate over a dict or list in Python

Posted by Chris Dutrow on Stack Overflow See other posts from Stack Overflow or by Chris Dutrow
Published on 2012-09-07T21:25:38Z Indexed on 2012/09/07 21:38 UTC
Read the original article Hit count: 228

Filed under:
|
|
|

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!

© Stack Overflow or respective owner

Related posts about python

Related posts about list