在 Python 3 中获取“OrderedDict”第一项的最短方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21062781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:57:49  来源:igfitidea点击:

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

pythonpython-3.xindexingiterable

提问by Ram Rachum

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

OrderedDict在 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?

有什么更好的建议吗?

回答by loa_in_

first = next #<hide this somewhere
first(ordered_dict.iteritems())

回答by Raymond Hettinger

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:

setdictOrderedDict、 generator 或其他不可索引的集合中获取元素的常用方法是:

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.

后者很好,因为next()函数允许您在集合为空时指定默认值,或者您可以选择让它引发异常。在接下来的()函数也是明确的,它是要求的下一个项目。

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]:

如果您确实需要索引和切片以及其他序列行为(例如索引多个元素),则使用list(some_collection)或将转换为列表是一件简单的事情[itertools.islice()][2]

s = list(some_collection)
print(s[0], s[1])

s = list(islice(n, some_collection))
print(s)

回答by ralien

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

使用popitem(last=False),但请记住,它会从字典中删除条目,即具有破坏性。

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.

有关更多详细信息,请查看集合手册。它也适用于 Python 2.x。

回答by Bryce Guinta

Subclassing and adding a method to OrderedDictwould be the answer to clarity issues:

子类化和添加一个方法OrderedDict将是清晰度问题的答案:

>>> o = ExtOrderedDict(('a',1), ('b', 2))
>>> o.first_item()
('a', 1)

The implementation of ExtOrderedDict:

的实施ExtOrderedDict

class ExtOrderedDict(OrderedDict):
    def first_item(self):
        return next(iter(self.items()))

回答by YitzikC

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

可读的代码使 OrderedDict 保持不变,并且不会为了获取第一项而不必要地生成一个潜在的大列表:

for item in ordered_dict.items():
    return item

If ordered_dict is empty, None would be returned implicitly.

如果ordered_dict 为空,则隐式返回None。

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:

与上面第一个示例对应的 Python 2.x 代码需要使用 iteritems() 代替:

for item in ordered_dict.iteritems():
    return item

回答by galaga4

First record:

第一条记录

[key for key, value in ordered_dict][0]

Last record:

最后记录

[key for key, value in ordered_dict][-1]