["python","dictionary"]
Return first N key:value pairs from dict

Consider the following dictionary, d: d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5} I want to return the first N key:value pairs from d (N <= 4 in this case). What is the most efficient method of doing this?
Prior to Python 3.6 there is no such thing a the "first n" keys because a dict doesn't remember which keys were inserted first. You can get first n iteration sorted key-value pairs though: n_items = take(n, d.items()) This uses the implementation of take from the itertools recipes: from itertools import islice def take(n, iterable): """Return the first n items of the iterable as a list.""" return list(islice(iterable, n)) See it working online: ideone For Python < 3.6 n_items = take(n, d.iteritems())