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

后端 未结 6 1018
庸人自扰
庸人自扰 2020-12-24 05:01

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

My best:

list(ordered_dict.items())[0]

Quite lo

6条回答
  •  青春惊慌失措
    2020-12-24 05:37

    Code that's readable, leaves the OrderedDict unchanged and doesn't needlessly generate a potentially large list just to get the first item:

    for item in ordered_dict.items():
        return item
    

    If ordered_dict is empty, None would be returned implicitly.

    An alternate version for use inside a stretch of code:

    for first in ordered_dict.items():
        break  # Leave the name 'first' bound to the first item
    else:
        raise IndexError("Empty ordered dict")
    

    The Python 2.x code corresponding to the first example above would need to use iteritems() instead:

    for item in ordered_dict.iteritems():
        return item
    

提交回复
热议问题