Why doesn't Python dict have .iter ()?

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 get an error message:

 AttributeError: 'dict' object has no attribute 'iter' 
+4
source share
3 answers

He has an iter . But you can just write

 for x in v_i: 
+12
source

Given the following dict :

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

You can simply iterate over the keys like this:

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

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

Explicit is better than implicit.

Python 2.x

What do you expect from a refund?

 >>> tuple(d.iter()) 

Too ambiguous, perhaps?

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

This seems like a reasonable approach.

What if you want to iterate over only the keys?

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

Nice! And the meanings?

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

What about keys and values ​​in the form of pairs (tuples)?

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

Python 3.x

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

 >>> tuple(d.keys()) ('a', 'c', 'b') >>> tuple(d.values()) (1, 3, 2) >>> tuple(d.items()) (('a', 1), ('c', 3), ('b', 2)) 
+16
source
 v_i.itervalues() 

You have iterkeys , iteritems and itervalues . Choose one.

+8
source

All Articles