How to sort a dictionary by key in Python

1 Answer

0 votes
import operator

dic = {'python': 13, 'php': 87, 'java': 6, 'c++': 2, 'c#': 81}

sorted_dic = sorted(dic.items(), key=operator.itemgetter(0))

print(sorted_dic)

'''
run:

[('c#', 81), ('c++', 2), ('java', 6), ('php', 87), ('python', 13)]

'''

 



answered Aug 30, 2018 by avibootz

Related questions

1 answer 117 views
2 answers 149 views
1 answer 113 views
2 answers 139 views
1 answer 152 views
1 answer 141 views
1 answer 121 views
...