Amazon Interview Question | How to sort a dictionary by key?
Question
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
It will take less than 1 minute to register for lifetime. Bonus Tip - We don't send OTP to your email id Make Sure to use your own email id for free books and giveaways
Answers ( 4 )
Use sorted function with a custom key
Sorted_list=sorted(dic.items(), key=lambda x: x[0])
mydict = {‘carl’:40,
‘alan’:2,
‘bob’:1,
‘danny’:3}
for key in sorted(mydict):
print(key, mydict[key])
We can use an in-built function sorted().
dict_1 = { “name”: “Kajal”, “age”: 27}
sorted(dict_1)