Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 308
mclafee Avatar asked Dec 01 '22 20:12

mclafee


1 Answers

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)
like image 188
Inbar Rose Avatar answered Dec 11 '22 04:12

Inbar Rose