Dictionaries have a method called items that returns a list of tuples, where each tuple is a
key-value pair.
d = {'a':10, 'b':20, 'c': 30} t = d.items() print t [('a', 10), ('c', 30), ('b', 20)]
As
you can see from previous example, the items are in no particular order. So in
this example we’ve started from defining a dictionary and then using built in
function itmes() transformed the dictionary in into a tuple. Since the list of
tuples is a list we can apply sort function on a list of tuples. Converting a dictionary
to a list of tuples is a way to output the contents of a dictionary sorted by
key.
d = {'a':10, 'b':20, 'c': 30} t = d.items() print "t = " + str(t) t.sort() print "list of tuples using sort() function" print " t = " + str(t)
The output of previous example is given below.
t = [('a', 10), ('c', 30), ('b', 20)] list of tuples using sort() function t = [('a', 10), ('b', 20), ('c', 30)]
The new list is sorted in ascending order by the key
value.
The in-built data structure Python offers are powerful. There are several applications and they free programmers from worrying about memory allocation etc. Find data structures and algorithms course. Keep sharing these amazing tutorials.
ReplyDeleteI am so grateful for your article.Really thank you! Really Cool.
ReplyDeleteP0wer bi onlinetraining from india
P0wer bi onlinetraining
P0wer bi training