Sort Dictionary Alphabetically When The Key Is A String (name)
Solution 1:
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)
Solution 2:
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
Solution 3:
i would do it like:
sorted_dict = {key: value for key, value in sorted(unsorted_dict.items())}
Solution 4:
Just to reiterate @hughdbrown's comment in a separate answer, because I missed it at first and believe it to be the true answer to this question:
You have a dictionary you want to sort alphabetically, say dictio
:
dictio = {'Beta': 2, 'alpha': 1}
sorted() will alphabetically sort the keys for you into a list, given that you convert all keys to lowercase (otherwise uppercase entries will be sorted first, then all lowercase):
sortedkeys = sorted(dictio, key=str.lower)
By calling the original dictionary again using that list of sorted keys you then can output it alphabetically:
foriinsortedkeys:
printdictio[i]
Solution 5:
dict1={"d":1,"a":3,"z":0}
x=sorted(dict1.items())
print(x)
output
[('a', 3), ('d', 1), ('z', 0)]
Post a Comment for "Sort Dictionary Alphabetically When The Key Is A String (name)"