Python 在按键排序的字典中迭代键/值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4550645/
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 16:16:45  来源:igfitidea点击:

Iterating over key/value pairs in a dict sorted by keys

python

提问by helpermethod

I have the following code, which just print the key/value pairs in a dict (the pairs are sorted by keys):

我有以下代码,它只是在字典中打印键/值对(这些对按键排序):

for word, count in sorted(count_words(filename).items()):
    print word, count

However, calling iteritems()instead of items()produces the same output

但是,调用iteritems()而不是items()产生相同的输出

for word, count in sorted(count_words(filename).iteritems()):
    print word, count

Now, which one should I choose in this situation? I consulted the Python tutorialbut it doesn't really answer my question.

现在,在这种情况下我应该选择哪一个?我查阅了Python 教程,但它并没有真正回答我的问题。

采纳答案by Mark Byers

In Python 2.x both will give you the same result. The difference between them is that itemsconstructs a list containing the entire contents of the dictionary whereas iteritemsgives you an iterator that fetches the items one at a time. In general iteritemsis a better choice because it doesn't require so much memory. But here you are sorting the result so it probably won't make any significant difference in this situation. If you are in doubt iteritemsis a safe bet. If performance really matters then measure both and see which is faster.

在 Python 2.x 中,两者都会给你相同的结果。它们之间的区别在于items构造一个包含字典全部内容的列表,而iteritems为您提供一个迭代器,一次获取一个项目。一般来说iteritems是更好的选择,因为它不需要太多内存。但是在这里您正在对结果进行排序,因此在这种情况下它可能不会产生任何显着差异。如果你有疑问iteritems是一个安全的赌注。如果性能真的很重要,那么测量两者并查看哪个更快。

In Python 3.x iteritemshas been removed and itemsnow does what iteritemsused to do, solving the problem of programmers wasting their time worrying about which is better. :)

在 Python 3.xiteritems中删除了,items现在做了iteritems以前做的事情,解决了程序员浪费时间担心哪个更好的问题。:)

As a side note: if you are counting occurrences of words you may want to consider using collections.Counterinstead of a plain dict (requires Python 2.7 or newer).

附带说明:如果您正在计算单词的出现次数,您可能需要考虑使用collections.Counter而不是普通的 dict(需要 Python 2.7 或更新版本)。

回答by Lennart Regebro

As per Marks answer: In Python 2, use iteritems(), in Python 3 use items().

根据 Marks 的回答:在 Python 2 中,使用iteritems(),在 Python 3 中使用items()

And additionally; If you need to support both (and don't use 2to3) use:

另外; 如果您需要同时支持(并且不使用2to3),请使用:

counts = count_words(filename)
for word in sorted(counts):
     count = counts[word]