How to sort dictionaries in python based on the keys?

0 votes
asked Aug 6, 2016 by Hitesh Garg (352 points)  

I have to sort a dictionary based on its values. I have a data of states and all its ministers in a dictionary and I want to sort a dictionary based on the states, how should I do this?
My data is like this -

x  = {'Delhi': ['name1', 'name2'],
     'Uttar Pradesh': ['name1'],
     'Tamil Nadu': ['name2'],
     'Assam': ['name3', 'name1']}

1 Answer

+1 vote
answered Nov 10, 2016 by Rahul Singh (543 points)  
selected Nov 24, 2016 by Hitesh Garg
Best answer

Since dictionary is a collection of randomly arranged pair of key and value you can not actually sort a dictionary itself but yes you can have a sorted view of the dictionary.
Possibly a list generated from the entries in a dictionary.

For example

import operator

x = {'Delhi': ['capital', 'state'],
     'Uttar Pradesh': "population",
     'Tamil Nadu': ['southern'],
     'Assam': ['mountains']}

# To sort dict based on values
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

# To sort dict based on KEYS
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

This has both the solution on how to sort the dictionary based on either key or values.
This returns a list of tuples.

This can be done using lambda functions in the following way -

x = {'Delhi': ['capital', 'state'],
     'Uttar Pradesh': "population",
     'Tamil Nadu': ['southern'],
     'Assam': ['mountains']}

# To sort dict based on KEYS
sorted_x = sorted(x.items(), key=lambda x: x[0])

# To sort dict based on VALUES
sorted_x = sorted(x.items(), key=lambda x: x[1])

Complete working example -

Hope it helps.

124 questions

41 answers


928 users

Most popular tags

java python python3 oracle database java-8 sql-server python2 oracle11g git oracle-12g command-line maven sql-server-2012 sql input array list fenitoina dilantin javaçš„ angular javascripts git-branch intellij-idea hashmap collection file-io io temovate clobetasol ampicillin principen daclatasvir daklinza vasotec enalapril nexium esomeprazole tadalafil tadlis sildenafil citrate pefomax xeloda capecitabina clobetasol temovate stemetil prochlorperazine methotrexate methotrexate sildenafilo y dapoxetina super kamagra norvasc amlodipine citalopram celexa amitriptylin saroten vitamin b12 methylcobalamin valaciclovir valtrex zudena udenafil sildenafil citrate vigour depakote divalproex retin-a tretinoine sildenafil citrate ip-max nizoral ketoconazol ciaton tadalafil norethisteronacetat aygestin indomethacin indocin tiova tiotropium bromid finasterida proscar lithium carbonate eskalith finasterida propecia levitra vardenafil vantin cefpodoxima loxitane loxapine rulide roxithromycine avodart dutasterid tecnomax sildenafil citrate methylcobalamin vitamin b12 permethrin acticin etinilestradiol norgestrel ovral pk-merz amantadin cycrin medroxyprogesterone serophene clomiphene spironolactone aldactone mesalazin pentasa zebeta bisoprolol cytodrox hydroxyurea ampicillin ampicillin pletal cilostazol paracetamol panadol pepcid famotidina meclizine hydrochloride antivert donaton tadalafil sdf dsfs sdgfgsdg mac null-pointer-exception constructor oracle-12c terminal hibernate-5 hibernate git-merge es6 programming git-amend git-commit java-stream git-remote multithreading access-modifiers nested-classes
Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.