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 f
Were d
is your dictionary and n
is the printing number:
for idx, (k, v) in enumerate(d):
if idx == n: break
print((k, v))
Casting your dictionary to list can be slow. Your dictionary may be too large and you don't need to cast all of it just for printing a few of the first.
Python's dict
s 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))
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())
This depends on what is 'most efficient' in your case.
If you just want a semi-random sample of a huge dictionary foo
, use foo.iteritems()
and take as many values from it as you need, it's a lazy operation that avoids creation of an explicit list of keys or items.
If you need to sort keys first, there's no way around using something like keys = foo.keys(); keys.sort()
or sorted(foo.iterkeys())
, you'll have to build an explicit list of keys. Then slice or iterate through first N keys
.
BTW why do you care about the 'efficient' way? Did you profile your program? If you did not, use the obvious and easy to understand way first. Chances are it will do pretty well without becoming a bottleneck.
def GetNFirstItems(self):
self.dict = {f'Item{i + 1}': round(uniform(20.40, 50.50), 2) for i in range(10)}#Example Dict
self.get_items = int(input())
for self.index,self.item in zip(range(len(self.dict)),self.dict.items()):
if self.index==self.get_items:
break
else:
print(self.item,",",end="")
Unusual approach, as it gives out intense O(N) time complexity.
For Python 3.8 the correct answer should be:
import more_itertools
d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
first_n = more_itertools.take(3, d.items())
print(len(first_n))
print(first_n)
Whose output is:
3
[('a', 3), ('b', 2), ('c', 3)]
After pip install more-itertools
of course.