且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python - 返回第一个N键:来自dict的值对

更新时间:2023-02-19 11:17:37

没有这样的东西是第一个n键,因为 dict 不记得首先插入了哪些键。

There's no such thing a the "first n" keys because a dict doesn't remember which keys were inserted first.

你可以得到任何键 - 价值对:

You can get any n key-value pairs though:

n_items = take(n, d.iteritems())

这使用 take docs.python.org/library/itertools.html#recipes> itertools 食谱

This uses the implementation of take from the itertools recipes:

from itertools import islice

def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))

看到它在线工作:ideone