Python - Return first N key:value pairs from dict

get first element of dictionary python 3
sort dictionary by value python
python dictionary
get first 10 elements of dictionary python
get first key, value pair in dictionary python
python get top 10 from dictionary
python sort dictionary by value descending
get last element of dictionary python

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?

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

Python, 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� Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. While using Dictionary, sometimes, we need to add or modify the key/value inside the dictionary.

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

Python - Return first N key:value pairs from dict, In this post: Getting first keys of a Python 3 dict; Getting first values of a Python 3 dictionary� Python - Return first N key:value pairs from dict (16 answers) Closed 2 years ago . I have a dictionary which the key are strings and the values are integers. im using a loop to print the an ordered vision of said dictionary.

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

Python 3 get first/last N elements of dictionary, Consider the following dictionary dd a 3 b 2 c 3 d 4 e 5I want to return the first N keyvalue pairs from d N lt 4 in this case What is Getting first or last elements of dictionary or map in python is not intuitive but is easy. We need to have two points in mind: * First maps are considered to be structures without order * second it's difficult to point the first and last element of a dictionary In this post: * Getting first keys of a Python 3 dict * Getting first values of a Python 3 dictionary * Getting first items of a

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

Python - Return first N key:value pairs from dict, If we print the dictionary again, we see a key-value pair with a colon between the key and The len function works on dictionaries; it returns the number of key- value pairs: + The first time you see a character, you would add an item to the dictionary. 'jan': 100} for key in counts: if counts[key] > 10 : print(key, counts[key ]). Return value: Borrowed reference. This is the same as the Python-level dict.setdefault(). If present, it returns the value corresponding to key from the dictionary p. If the key is not in the dict, it is inserted with value defaultobj and defaultobj is returned.

Did not see it on here. Will not be ordered but the simplest syntactically if you need to just take some elements from a dictionary.

n = 2
{key:value for key,value in d.items()[0:n]}

9. Dictionaries � Python for person in everybody, How can I print the 10 biggest values from a Python dictionary where key a string, a substring they wish to find and another string they wish to replace the found In this way though you have to sort the whole values in the dictionary first ,� For printing the keys and values, we can either iterate through the dictionary one by one and print all key-value pairs or we can print all keys or values at one go. For this tutorial, we are using python 3. Print all key-value pairs using a loop : This is the simplest way to print all key-value pairs of a dictionary.

How to print the 10 biggest values from a Python dictionary where key, A dictionary is an unordered and mutable Python container that stores Dictionaries are written with curly brackets ({}), including key-value pairs separated by… First, we have to build an iterator of tuples using zip(*iterables) function. This method returns the value for key if key is in the dictionary, else� Append a new key value pair in dictionary # Adding a new key value pair wordFreqDic.update( {'before' : 23} ) It will add a new key value pair in the dictionary. Dictionary contents will be now test :: 43 this :: 43 Hello :: 56 at :: 23 before :: 23 If key is string you can directly add without curly braces i.e. # Adding a new key value pair

15 things you should know about Dictionaries in Python, Updates the dictionary with the key/value pairs from other , overwriting existing keys. values(), Returns a new object of the dictionary's values. Here are a few� Dictionary in Python - Creating a dictionary is as simple as placing items inside curly braces {} separated by comma. An item has a key and the corresponding value expressed as a pair, key: value.

Python Dictionary (With Examples), A Dictionary in Python is a collection of Key-Value pairs. The “\n” in the first print statement ensures that a blank line is inserted before each� I always use nested list and dictionary comprehension for unstructured data and this is a common way I use it. In [14]: data = """ 41:n 43:n 44:n 46:n 47:n 49:n 50:n 51:n 52:n 53:n 54:n 55:cm 56:n

Comments
  • Caution. Seems to be a lot of misinformation in answers. My tests show not a single solution is faster than list(d.items())[:4]. list() is the underlying implementation for many of the answers.
  • I believe iteritems should be replaced with items for folks on Python 3
  • @MonicaHeddneck, brilliant, thank you for adding this comment.
  • Beginner here - is take() a part of the python code base anywhere? Or, is it purely the function you defined in your answer here? Asking as if it's a part of the code base, I'm not able to find/import it. :)
  • This one is a better solution if you want to select N many key:value pairs as a dictionary, not as a list
  • @fermat4214 Is it an issue, if my entire dictionary prints out when I run any of these commands?
  • list(mydict)[:2] is wasteful if you don't need to sort the dictionary and only need the first 2 elements. What if the dictionary has 1 mil k-v pairs? Converting the whole thing to a list is expensive. Mark Byers's solution is much better.
  • This should be the solution !
  • Not looking lazy. Takes 2x longer than `list(d.items())[:4]
  • Fantastic answer, this is the only answer on this page that worked for me and is also readable. Also, I can verify this works with Python 3, which some of the older answers don't seem to.
  • I tried you code but I get this error: TypeError: 'dict_items' object is not subscriptable {key:value for key,value in stocks.items()[0:n]} (stocks is the name of my dictionary)