0

Suppose this is my dictionary

test = {1:'a',2:'b',3:'c',4:'d',5:'e'}

How do I print first 3 elements of it using a for loop?

jpp
  • 159,742
  • 34
  • 281
  • 339
  • 1
    Dictionaries in python 2.7 are not ordered. Therefore, you have to define what you mean by "first 3 elements". – jpp Jan 26 '18 at 14:10

2 Answers2

1

This solution assumes that by "first 3 elements" you mean "first 3 elements sorted by key".

test = {1:'a',2:'b',3:'c',4:'d',5:'e'}

in_scope = set(sorted(test)[:3])
print({k: v for k, v in test.items() if k in in_scope})

# {1: 'a', 2: 'b', 3: 'c'}

Note: this works in python 3.6+ since dictionaries are naturally ordered. For better performance use a heap queue instead of sorting all keys and then list slicing.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • This involves sorting `test` `len(test)` times. Surely the simpler solution would just be `print(dict(sorted(test.items())[:3]))`, which only sorts once. – ShadowRanger Apr 09 '19 at 00:21
  • @ShadowRanger, Good point, I've just separated it out so sorting isn't repeated. Better to use a heap queue if performance is important. – jpp Apr 09 '19 at 08:19
1

In Python dictionaries are by nature unordered in order to do what you want you would need to create an Ordered dictionary which remembers the order that key value pairs are inserted. Here is some sample code to do what you wish

import collections
test = {1:'a',2:'b',3:'c',4:'d',5:'e'}
blah = collections.OrderedDict(test)
for x in range(3):
    print(blah.items()[x])

If this was python 3 you would have to wrap the blah.items() call in a list as it returns an iterable object view. Here is a link for more info Accessing Items In a ordereddict

Matthew Barlowe
  • 2,229
  • 1
  • 14
  • 24
  • although an "implementation detail", by nature dictionaries in python 3.6 are ordered: https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation – jpp Jan 27 '18 at 01:21