-1

So i have dictionary like this

   mydic={
    'a':3,
    'b':1,
    'c':2,}
    def sortedby():
        sort= (sorted(mydic.items(), key = lambda t : t[0]))


        return(sort)
    print(sortedby())

I would like to get it returned not as list or int but as dictionary

bozz
  • 21
  • 3
  • 9

1 Answers1

2

Python's dict are not ordered. In order to maintain the order in the dict, you should use collections.OrderedDict:

from collections import OrderedDict

mydic = {
    'a':3,
    'b':1,
    'c':2,}
ordered_dict = OrderedDict(sorted(mydic.items(), key=lambda t: t[0]))
# Store dict as: OrderedDict([('a', 3), ('b', 1), ('c', 2)])
#                 Sorted        ^         ^         ^
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126