mclafee
mclafee

Reputation: 1426

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? safe?

Upvotes: 5

Views: 3547

Answers (4)

dmg
dmg

Reputation: 7716

Although this was already mentioned, I wanted to add some exact numbers to these discussion. 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 items was used (float keys) and I used timeit with 100 repetitions. These 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 downsides in Python 2.x

Upvotes: 5

Inbar Rose
Inbar Rose

Reputation: 43467

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 in dict.items():
    # k is the key
    # v is the value
    print '%s: %s' % (k, v)

Upvotes: 11

warvariuc
warvariuc

Reputation: 59664

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.

Upvotes: 0

Fabian
Fabian

Reputation: 4348

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

Upvotes: 3

Related Questions