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'
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.
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With