Skip to content Skip to sidebar Skip to footer

Accessing Python Dict Keys With Or Without Dict.keys()

Usually I access dict keys using 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? saf

Solution 1:

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

To answer the question you didn't know you had:

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

But doing for k in dict iterates over them.

Iterating is faster than constructing a list.

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

Most dictionary needs can usually be solved by iterating over the items() instead of by keys in the following manner:

for k, v indict.items():
    # k is the key# v is the valueprint'%s: %s' % (k, v)

Solution 2:

Although this was already mentioned, I wanted to add some exact numbers to these discussion. So I compared:

defiter_dtest(dtest):
    for i in dtest:
        pass

and

deflist_dtest(dtest):
    for i in dtest.keys():
        pass

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

Python 2.7.1:iter_dtest:3.92487884435slist_dtest:6.24848171448sPython 3.2.1:iter_dtest:3.4850587113842555slist_dtest:3.535072302413432s

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

Solution 3:

The second code example's behaviour is equal to calling .keys(), so yes, this is correct and safe.

Solution 4:

It's not the same.

for k in d: print k

does not create additional list, while

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.

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

Post a Comment for "Accessing Python Dict Keys With Or Without Dict.keys()"