How to get first/last N elements of dictionary in Python

Getting the first or last element of a dictionary Python is not intuitive operation but it is easy.

We need to have two points in mind:

  • First dictionary in Python is designed to be a structure without order
  • Second it's difficult to point the first and last element of a Dictionary
  • Starting with Python 3.6 dict will keep the insert order of elements - check the experiment described in step 5.

Step 1: Get first key of a Python 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

Step 2: Get first value of a Python dictionary

First value or element of a dictionary in Python can be extracted by code like:

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

Step 3: Getting first items of a Python 3 dict

When order of the elements is not important all items can be get and extracted by:

mydict = {1:'a',2:'b',3:'c',4:'d',5:'e'}
for i in mydict.items():
    print(i)

this will produce:

(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
(5, 'e')

It's possible to use the list method to extract the first 3 keys - list(mydict)[0:3]. So extracting first 3 elements from dictionary is done by extracting first keys and getting their values:

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  

Step 4: Get last elements of a Python dictionary with order

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 of a Python dict in different order. For example, the next code is getting the last N items 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

Step 5: Experiment: Python get elements of dictionary after update, add and delete

Let's do a quick experiment in Python 3.7. First let's create a simple dictionary:

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

and list all elements by:

for i in mydict.items():
    print(i)
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
(5, 'e')

Now let's add a new element by:

mydict[0] = 'z'

Can you guess the output of the previous command? If you think that element (0, 'z') will be the last one. Congratulations! You are a good programmer!

(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
(5, 'e')
(0, 'z')

Now let's delete element with key 3 and value c of the same dictionary by:

mydict.pop(3)

order is:

(1, 'a')
(2, 'b')
(4, 'd')
(5, 'e')
(0, 'z')

and what if we add it again?

mydict[3] = 'c'

Is it going to be in the same place or at the end?

(1, 'a')
(2, 'b')
(4, 'd')
(5, 'e')
(0, 'z')
(3, 'c')

Of course this doesn't prove anything and shouldn't be taken as granted. There's no guarantee that the order of a Python dictionary is preserved. It might depend on many factors like Python version, parallelism etc.

Note 1: Since Python 3.6 the dictionary should preserve order of insert!

Note 2: Have in mind that there are structures like: from collections import OrderedDict which can be used when order is important.

Share Tweet Send
0 Comments
Loading...