Home > Back-end >  Return the first item of a dictionar as a dictionary in Python?
Return the first item of a dictionar as a dictionary in Python?

Time:09-23

Let's assume we have a dictionary like this:

>>> d={'a': 4, 'b': 2, 'c': 1.5}

If I want to select the first item of d, I can simply run the following:

>>> first_item = list(d.items())[0]
('a', 4)

However, I am trying to have first_item return a dict instead of a tuple i.e., {'a': 4}. Thanks for any tips.

CodePudding user response:

Use itertools.islice to avoid creating the entire list, that is unnecessarily wasteful. Here's a helper function:

from itertools import islice

def pluck(mapping, pos):
    return dict(islice(mapping.items(), pos, pos   1))

Note, the above will return an empty dictionary if pos is out of bounds, but you can check that inside pluck and handle that case however you want (IMO it should probably raise an error).

>>> pluck(d, 0)
{'a': 4}
>>> pluck(d, 1)
{'b': 2}
>>> pluck(d, 2)
{'c': 1.5}
>>> pluck(d, 3)
{}
>>> pluck(d, 4)
{}

Note, accessing an element by position in a dict requires traversing the dict. If you need to do this more often, for arbitrary positions, consider using a sequence type like list which can do it in constant time. Although dict objects maintain insertion order, the API doesn't expose any way to manipulate the dict as a sequence, so you are stuck with using iteration.

CodePudding user response:

Dictionary is a collections of key-value pairs. It is not really ordered collection, though since python 3.7 it keeps the order in which keys were added.

Anyway if you really want some "first" element you can get it in this manner:

some_item = next(iter(d.items()))

You should not convert it into a list because it will eat much (O(n)) memory and walk through whole dict as well.

Anyway I'd recommend not to think that dictionary has "first" element. It has keys and values. You can iterate over them in some unknown order (if you do not control how it is created)

  • Related