Python 3 get first/last N elements of dictionary

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

If the order of the elements is not important for you then you can get several N elements of a dictionary by next code example:

mydict = {1:'a',2:'b',3:'c',4:'d',5:'e'}
for x in list(mydict)[0:3]:
    print (x)

result:

1
2
3

Getting first values of a Python 3 dictionary

If the order of the elements is not important for you then you can get several N elements of a dictionary by next code example:

mydict = {1:'a',2:'b',3:'c',4:'d',5:'e'}
for x in list(mydict)[0:3]:
    print (mydict[x])

result:

a
b
c

Getting first items of a Python 3 dict

If the order of the elements is not important for you then you can get several N elements of a dictionary by next code example:

mydict = {1:'a',2:'b',3:'c',4:'d',5:'e'}
for x in list(mydict)[0:3]:
    print ("key {}, value {} ".format(x,  mydict[x]))

result:

key 1, value a 
key 2, value b 
key 3, value c  

Getting last items of a Python 3 dictionary

If the order is important for you then you can use additional methods like:

  • sorted - ascending order
  • reversed - descending order

This will help you to get the elements in different order. For example next code is getting last N keys from a dictionary in Python.

mydict = {1:'a',2:'b',3:'c',4:'d',5:'e'}
for x in list(reversed(list(mydict)))[0:3]:
    print (x)

result:

5
4
3

Related Article