The Python Oracle

Return first N key:value pairs from dict

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4

--

Chapters
00:00 Return First N Key:Value Pairs From Dict
00:22 Accepted Answer Score 171
00:59 Answer 2 Score 19
01:40 Answer 3 Score 147
02:29 Answer 4 Score 15
02:42 Thank you

--

Full question
https://stackoverflow.com/questions/7971...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary

#avk47



ACCEPTED ANSWER

Score 171


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



ANSWER 2

Score 147


A very efficient way to retrieve anything is to combine list or dictionary comprehensions with slicing. If you don't need to order the items (you just want n random pairs), you can use a dictionary comprehension like this:

# Python 2
first2pairs = {k: mydict[k] for k in mydict.keys()[:2]}
# Python 3
first2pairs = {k: mydict[k] for k in list(mydict)[:2]}

Generally a comprehension like this is always faster to run than the equivalent "for x in y" loop. Also, by using .keys() to make a list of the dictionary keys and slicing that list you avoid 'touching' any unnecessary keys when you build the new dictionary.

If you don't need the keys (only the values) you can use a list comprehension:

first2vals = [v for v in mydict.values()[:2]]

If you need the values sorted based on their keys, it's not much more trouble:

first2vals = [mydict[k] for k in sorted(mydict.keys())[:2]]

or if you need the keys as well:

first2pairs = {k: mydict[k] for k in sorted(mydict.keys())[:2]}



ANSWER 3

Score 19


Python's dicts are not guaranteed to be ordered in Python <= 3.6, so it's meaningless to ask for the "first N" keys in older Python versions.

The collections.OrderedDict class is available if that's what you need. You could efficiently get its first four elements as

import itertools
import collections

d = collections.OrderedDict((('foo', 'bar'), (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')))
x = itertools.islice(d.items(), 0, 4)

for key, value in x:
    print key, value

itertools.islice allows you to lazily take a slice of elements from any iterator. If you want the result to be reusable you'd need to convert it to a list or something, like so:

x = list(itertools.islice(d.items(), 0, 4))



ANSWER 4

Score 15


foo = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
iterator = iter(foo.items())
for i in range(3):
    print(next(iterator))

Basically, turn the view (dict_items) into an iterator, and then iterate it with next().