Access to Python key keys with or without dict.keys ()

I usually get dict keys using the keys() method:

 d = {'a':1, 'b':2, 'c':3} for k in d.keys(): print k 

But sometimes I see this code:

 for k in d: print k 

Is this code correct? safely?

+4
source share
4 answers

Although this has already been mentioned, I wanted to add some exact numbers to these discussions. So I compared:

 def iter_dtest(dtest): for i in dtest: pass 

and

 def list_dtest(dtest): for i in dtest.keys(): pass 

A dictionary with 1,000,000 elements (float keys) was used, and I used timeit with 100 repetitions. Here are the results:

 Python 2.7.1: iter_dtest: 3.92487884435s list_dtest: 6.24848171448s Python 3.2.1: iter_dtest: 3.4850587113842555s list_dtest: 3.535072302413432s 

Obviously, calling dtest.keys() has some flaws in Python 2.x

+4
source

To answer your explicit question, yes, it is safe.

To answer a question that you did not know, you had:

in python 2.x: dict.keys() returns a list of keys.

But doing for k in dict iteration over them.

Iteration is faster than creating a list.

in python 3+, explicitly calling dict.keys() not slower because it also returns an iterator.

Most dictionary needs can usually be solved by iterating over items() instead of keys as follows:

 for k, v in dict.items(): # k is the key # v is the value print '%s: %s' % (k, v) 
+11
source

The second code example is the .keys() call, so yes, it is correct and safe.

+3
source

This is not the same.

 for k in d: print k 

does not create an additional list, but

 for k in d.keys(): print k 

creates another list and then iterates over it

At least in Python 2. In Python 3, dict.keys() is an iterator.

That way you can use either for k in d.iterkeys() or for k in d . Both results lead to the same result.

0
source

All Articles