考虑下面的字典d:
d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}我想从d返回前N个键:值对(在本例中是N <= 4)。执行此操作的最有效方法是什么?
发布于 2011-11-02 03:18:17
没有“前n”个键这样的东西,因为dict不会记住哪个键是首先插入的。
不过,您可以获得任意n个键-值对:
n_items = take(n, d.iteritems())这使用itertools recipes中的take实现
from itertools import islice
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(islice(iterable, n))在线查看它的工作方式:ideone
Python3.6的更新
n_items = take(n, d.items())https://stackoverflow.com/questions/7971618
复制相似问题