• Linux
  • FreeBSD
  • Networking
  • Python
  • AWS
  • WebDev
  • About Us

How to convert Dictionary to a Tuple in Python

Written by
Python Leave a Comment

Sometimes you may need to sort the order of your items in a dictionary which is not possible by default . In this case you need to convert your dict to a list of Tuples .

First you need a module called operator which comes with Python3 or you can install it with ‘pip’

‘abc’ is my dictionary , so we need a new variable called ‘sortedabc’ for the list of tuples .

sorted(abc.items()) will convert the dictionary to tuples . For the key value , you need to specify the value of the dictionary and you use the itemgetter from the ‘operator’ module . As you know the dictionary key-value pair . The index (1) is the value of the dictionary which you are using as the key .

Once you have the dictionary sorted to a list you can re arrange the order. For eg : if you want to sort this tuple in a descending order, add a reverse funtion at the end :

© Copyright 2020.TechieNix. All Rights Reserved.