Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (3.5k points)
edited by
I have two fields a string field and a numeric field in a directory. The key of the dictionary as well as the string field is unique.

how can I sort them based on values, I can do the sort based on the keys?

1 Answer

0 votes
by (46k points)
edited by

You need an ordered data type to represent the sorted values (probably a list of tuples) as it's not possible to sort a directory because they are orderless whereas list and tuples aren't. Ex.

import operator
y = {2: 3, 4: 5, 5: 4, 3: 2, 1: 1}
sorted_y = sorted(y.items(), key=operator.itemgetter(1))

 A list of tuples, here sorted_x will be sorted by first element in each tuple dict(sorted_y) == y

If you want to sort the keys instead of values, use

import operator
y = {2: 3, 4: 5, 5: 4, 3: 2, 1: 1}
sorted_y = sorted(y.items(), key=operator.itemgetter(1))

Hope this helps.

P.S. Only works in the Python versions below 3.0 

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

Related questions

0 votes
2 answers
asked Aug 23, 2019 in Python by Sammy (47.6k points)
+3 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Jul 2, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...