Python Sort Dictionaries By Key Name

Sort Python Dictionary According To Keys Name In Ascending Or Descending Order Using Single Line Code dict( [ [x,s[ x ] ] for x in sorted( list(s) ) ] ). There Is No Built-In Function In Python 3.8 Version For Sort Dictionary Data Type According To Key But We Can Sort It Manually Using List Sortion.

Sort Dictionary By Keys Using Single Line Code.

  • Convert Python Dict Into List Of Keys Using List Function i.e:- list(User_dict)
  • Sort Keys List By Default In Ascending Order Using Python InBuild Sorted Function i.e:-sorted(list(User_dict))
  • After That Apply List Commprehansion On Sorted List Of Keys And Collect Key And Value In Nested List. i.e:- [[x,User.pop(x)] for x in sorted(list(User))]
  • Moving Furter Convert That List Comprehension Into Dict Using dict() Function.

User = {
        "Name":"Shivjeet",
        "Age":21,
        "Language":"Python"
        }
# Sort Dict In Ascending Order

User = dict([[x,User.pop(x)] for x in sorted(list(User))])

print(User)

Sort Dict In Descending Order According to Keys

Similarly, It Is Possible To Sort Dictionary In Descending Order Manually. Just Add reverse=True Argument In Python Sorted Function I.e:- sorted(reverse=True) As Shown In Code Below:-

User = {
        "Name":"Shivjeet",
        "Age":21,
        "Language":"Python"
        }
# Sort Dict In Ascending Order

User = dict([[x,User.pop(x)] for x in sorted(list(User),reverse=True)])

print(User)

Thank you