2

I was wondering how exactly the for loop accesses keys in a dictionary ? does it call dict.keys() and iterate through that list ?

The reason I'm asking is that I want to query a dictionary's key, any key, and I was wondering if there is a difference in performance (aside from visuals and readability) between calling:

for key in dict:
    my_func(dict[key])
    break

and

my_func(dict.keys()[0]) 

Which brought me to the above question - what does python do during a for loop on dicts, specifically, under the hood?

deepbrook
  • 2,523
  • 4
  • 28
  • 49
  • `dict[key]` is the same as `dict.keys()[0]` ? in OP `dict[key]` is supposed to return a value, while `dict.keys()[0]` supposed to return a key – Hacketo Mar 23 '16 at 09:51
  • 1
    Check out the iterator protocol in [PEP 234](https://www.python.org/dev/peps/pep-0234/) – miradulo Mar 23 '16 at 09:51
  • Are you asking or telling? Since `dicts` are unordered they wouldn't be the same, if at all by accident or luck or whatever. – deepbrook Mar 23 '16 at 09:52

1 Answers1

2

Iterating dict does not call dict.key(). The dictionary itself support iteration.

>>> iter({'name': 'value'})
<dict_keyiterator object at 0x7f127da89688>

BTW, dict.keys in Python 3.x returns dictionary key view which does not support indexing.

>>> {'name': 'value'}.keys()
dict_keys(['name'])
>>> {'name': 'value'}.keys()[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict_keys' object does not support indexing

If you want to get any key, you can use next, iter:

>>> next(iter({'name': 'value', 'name2': 'another value'}))
'name'

>>> next(iter({}))  # <--  To handle empty case, pass default value
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> next(iter({}), 'default value')
'default value'
falsetru
  • 357,413
  • 63
  • 732
  • 636