python – Sort dictionary alphabetically when the key is a string (name)

python – Sort dictionary alphabetically when the key is a string (name)

simple algorithm to sort dictonary keys in alphabetical order, First sort the keys using sorted

sortednames=sorted(dictUsers.keys(), key=lambda x:x.lower())

for each key name retreive the values from the dict

for i in sortednames:
   values=dictUsers[i]
   print(Name=  + i)
   print (   Age=  + values.age)
   print (   Address=  + values.address)
   print (   Phone Number=  + values.phone)

i would do it like:

sorted_dict = {key: value for key, value in sorted(unsorted_dict.items())}

python – Sort dictionary alphabetically when the key is a string (name)

dictio = { Epsilon:5, alpha:1, Gamma:3, beta:2, delta:4 }

sortedDict = dict( sorted(dictio.items(), key=lambda x: x[0].lower()) )

for k,v in sortedDict.items():
    print({}:{}.format(k,v))

output

 alpha:1
 beta:2
 delta:4
 Epsilon:5
 Gamma:3

Leave a Reply

Your email address will not be published. Required fields are marked *