Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to get first item of `OrderedDict` in Python 3

What's the shortest way to get first item of OrderedDict in Python 3?

My best:

list(ordered_dict.items())[0] 

Quite long and ugly.

I can think of:

next(iter(ordered_dict.items()))       # Fixed, thanks Ashwini 

But it's not very self-describing.

Any better suggestions?

like image 691
Ram Rachum Avatar asked Jan 11 '14 13:01

Ram Rachum


People also ask

How do I get the first key from an ordered dictionary?

In Python versions 3.7 and above, where a dictionary is ordered, we can get the first key, by first converting the dictionary into an iterated object using iter() function and then fetching its first index key using the next function.

Is OrderedDict slower than dict?

OrderedDict is over 80% slower than the standard Python dictionary (8.6/4.7≈1.83).

What is OrderedDict ()?

An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict() and OrderedDict() is that: OrderedDict preserves the order in which the keys are inserted.

How is the ordered dict preserving order?

Python's OrderedDict is a dict subclass that preserves the order in which key-value pairs, commonly known as items, are inserted into the dictionary. When you iterate over an OrderedDict object, items are traversed in the original order. If you update the value of an existing key, then the order remains unchanged.


2 Answers

Programming Practices for Readabililty

In general, if you feel like code is not self-describing, the usual solution is to factor it out into a well-named function:

def first(s):     '''Return the first element from an ordered collection        or an arbitrary element from an unordered collection.        Raise StopIteration if the collection is empty.     '''     return next(iter(s)) 

With that helper function, the subsequent code becomes very readable:

>>> extension = {'xml', 'html', 'css', 'php', 'xhmtl'} >>> one_extension = first(extension) 

Patterns for Extracting a Single Value from Collection

The usual ways to get an element from a set, dict, OrderedDict, generator, or other non-indexable collection are:

for value in some_collection:     break 

and:

value = next(iter(some_collection)) 

The latter is nice because the next() function lets you specify a default value if collection is empty or you can choose to let it raise an exception. The next() function is also explicit that it is asking for the next item.

Alternative Approach

If you actually need indexing and slicing and other sequence behaviors (such as indexing multiple elements), it is a simple matter to convert to a list with list(some_collection) or to use [itertools.islice()][2]:

s = list(some_collection) print(s[0], s[1])  s = list(islice(n, some_collection)) print(s) 
like image 183
Raymond Hettinger Avatar answered Sep 21 '22 14:09

Raymond Hettinger


Use popitem(last=False), but keep in mind that it removes the entry from the dictionary, i.e. is destructive.

from collections import OrderedDict o = OrderedDict() o['first'] = 123 o['second'] = 234 o['third'] = 345  first_item = o.popitem(last=False) >>> ('first', 123) 

For more details, have a look at the manual on collections. It also works with Python 2.x.

like image 37
ralien Avatar answered Sep 23 '22 14:09

ralien