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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With