Amazon Interview Question | How to sort a dictionary by key?

Question

with example

in progress 0
TheDataMonk 55 years 4 Answers 1833 views Grand Master 0

Answers ( 4 )

  1. Use sorted function with a custom key
    Sorted_list=sorted(dic.items(), key=lambda x: x[0])

  2. mydict = {‘carl’:40,
    ‘alan’:2,
    ‘bob’:1,
    ‘danny’:3}

    for key in sorted(mydict):
    print(key, mydict[key])

  3. We can use an in-built function sorted().

  4. dict_1 = { “name”: “Kajal”, “age”: 27}
    sorted(dict_1)

Leave an answer

Browse
Browse