Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 351
Chris Dutrow Avatar asked Sep 07 '12 21:09

Chris Dutrow


People also ask

Is it faster to iterate through a list or dictionary?

Analysis Of The Test Run ResultA dictionary is 6.6 times faster than a list when we lookup in 100 items.

Can you iterate over a dictionary in Python?

You can iterate through a Python dictionary using the keys(), items(), and values() methods. keys() returns an iterable list of dictionary keys. items() returns the key-value pairs in a dictionary. values() returns the dictionary values.

What does Iteritems do in Python?

The iteritems() method generates an iterator object of the DataFrame, allowing us to iterate each column of the DataFrame. Note: This method is the same as the items() method. Each iteration produces a label object and a column object. The label is the column name.


1 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}
like image 200
DSM Avatar answered Sep 30 '22 20:09

DSM