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())
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))
See it working online: ideone
Update for Python 3.6
n_items = take(n, d.items())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…