Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return first N key:value pairs from dict

People also ask

How do I find the first key-value pair in a dictionary?

In Python, there are a few different ways we can get the first key/value pair of a dictionary. The easiest way is to use the items() function, convert it to a list, and access the first element. If you only care about getting the first value of a dictionary, you can use the dictionary values() function.

How do I print the first element in a dictionary?

Method #3 : Using For Loop : This can be done using for loop. In this method run a for loop get first key and break the loop and print first key of the dictionary.

Which method returns the key-value pairs in a dictionary?

items() This method returns a list of a dictionary's key-value pairs.

How do you get all the keys values from a dict?

In Python to get all values from a dictionary, we can use the values() method. The values() method is a built-in function in Python and returns a view object that represents a list of dictionaries that contains all the values. In the above code first, we will initialize a dictionary and assign key-value pair elements.


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

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]}

To get the top N elements from your python dictionary one can use the following line of code:

list(dictionaryName.items())[:N]

In your case you can change it to:

list(d.items())[:4]

Python's dicts are not ordered, so it's meaningless to ask for the "first N" keys.

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

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