Iterate over a dict or list in Python

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!

Answers


I've never needed to do this, ever. But if I did, I'd probably do something like this:

seq_iter = x if isinstance(x, dict) else xrange(len(x))

For example, in function form:

>>> def seq_iter(obj):
...     return obj if isinstance(obj, dict) else xrange(len(obj))
... 
>>> x = [1,2,3]
>>> for i in seq_iter(x):
...     x[i] = 99
... 
>>> x
[99, 99, 99]
>>> 
>>> x = {1: 2, 2:3, 3:4}
>>> for i in seq_iter(x):
...     x[i] = 99
... 
>>> x
{1: 99, 2: 99, 3: 99}

Need Your Help

use perl to extract specific output lines

perl sed prolog nlp output

I'm endeavoring to create a system to generalize rules from input text. I'm using reVerb to create my initial set of rules. Using the following command[*], for instance:

nodejs' spawn and exec using pdf2swf

node.js flash exec spawn pdf2swf

I hope that there is someone that can help with this problem since I don't get it myself.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.