user9272732
user9272732

Reputation:

How to access specific elements of a dictionary

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?

Upvotes: 0

Views: 124

Answers (2)

jpp
jpp

Reputation: 164783

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.

Upvotes: 1

Matthew Barlowe
Matthew Barlowe

Reputation: 2328

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

Upvotes: 1

Related Questions