Return first N key:value pairs from 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())

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())

Leave a Comment