Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come Python's dict doesn't have .iter()?

Tags:

python

def complicated_dot(v, w):
        dot = 0
        for (v_i, w_i) in zip(v, w):
            for x in v_i.iter():
                if x in w_i:
                    dot += v_i[x] + w_i[x]
        return float(dot)

I'm getting an error that says:

AttributeError: 'dict' object has no attribute 'iter'
like image 291
TIMEX Avatar asked Nov 28 '22 01:11

TIMEX


1 Answers

Considering the following dict:

>>> d
{'a': 1, 'c': 3, 'b': 2}

You can just iterate over the keys like so:

>>> for k in d:
...     print(k, d[k])
... 
('a', 1)
('c', 3)
('b', 2)

This implicitly calls the special method __iter__(), but remember:

Explicit is better than implicit.

Python 2.x

What would you expect the following to return?

>>> tuple(d.iter())

Too ambiguous, perhaps?

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'iter'

That seems like a perfectly reasonable approach.

What if you wanted to iterate over just the keys?

>>> tuple(d.iterkeys())
('a', 'c', 'b')

Nice! And the values?

>>> tuple(d.itervalues())
(1, 3, 2)

How about the keys and values as pairs (tuples)?

>>> tuple(d.iteritems())
(('a', 1), ('c', 3), ('b', 2))

Python 3.x

Things are slightly different, the objects returned by dict.keys(), dict.values() and dict.items() are view objects. These can be used in much the same way, though:

>>> tuple(d.keys())
('a', 'c', 'b')
>>> tuple(d.values())
(1, 3, 2)
>>> tuple(d.items())
(('a', 1), ('c', 3), ('b', 2))
like image 199
Johnsyweb Avatar answered Nov 29 '22 13:11

Johnsyweb