Search code examples
pythonfor-loopindexingitems

How do I index f.items()?


I could run a for loop as such:

for v in f.items():

BUT, it takes too much time. I know I want the second object in f.items(). How to I directly get the second object and save it?

Im not sure what the syntax is: e.g is it f.items(2), f.items()[2]? None of these work so I was wondering what does.


Solution

  • You can create a list and then index.

    item = list(f.items())[1]
    

    Lists are created often in python and this operation is relatively inexpensive. If your dictionary is large, you can create an iterator and take its second value.

    i = iter(f.items())
    next(i)
    item = next(i)
    

    But the dict would need to be rather large to make this the better option.