Python Dictionary Sort (11 Examples)

文章推薦指數: 80 %
投票人數:10人

Python sort dictionary by value then key Skiptocontent InthisPythontutorial,wewilldiscussPythonDictionarysort.Wewillseehere,howtosortadictionaryinPython,howtosortdictionaryinpythonbykeyandvalue,andthebelowexamples: PythondictionarysortbyvaluePythondictionarysortbykeyPythondictionarysortbyvaluedescendingPythondictionarysortbyvaluealphabeticallyPythondictionarysortbykeyalphabeticallyPythondictionarysortreversePythondictionarysortbykeyvaluePythondictionarysortwithlambdaPythondictionarysortbyalphabeticallyPythondictionarysortbyvaluelistPythonsortdictionarybyvaluethenkey TableofContents show 1. HowtosortdictionaryinPython 2. CheckPythondictionarysort–Anotherapproach 3. Pythondictionarysortbyvalue 4. Pythondictionarysortbyvalue–Anotherexample 5. PythonDictionarysortbykey 6. HowtosortadictionarykeysinPython–Anotherapproach 7. PythondictionarysortbyvalueDescending 8. Pythondictionarysortbyvaluealphabetically 9. Pythondictionarysortbykeyalphabetically 10. Pythondictionarysortreverse 11. HowtoreversetheorderofkeysinPythondictionary 12. Pythondictionarysortbykeyvalue 13. Pythondictionarysortwithlambda 14. Pythondictionarysortbyalphabetically 15. Pythondictionarysortbyvaluelist 16. Pythonsortdictionarybyvaluethenkey HowtosortdictionaryinPython InPythonsorted()isthebuilt-infunctionthatcanbehelpfultosortalltheiterablesinPythondictionary.Tosortthevaluesandkeyswecanusethesorted()function.Thissortedfunctionwillreturnanewlist. Syntax: HereistheSyntaxofthesorted()function. sorted ( iterable, Key=None, reverse=False ) Itconsistsoffewparametersiterable:Thisfunctioncanbeusedonalliterablesinaascendingorder.Key:Ifyouwanttomodifythesortingprocessthenyoucanusethiskeyfunctionbydefaultitsvaluewillbenone.reverse:Hereyoucanseereverse=False.ItisforascendingorderandifyouwantnumbersinthedescendingorderthenyoucansetthisreverseflagorderastrueNote:Ifyoudecidethatyouarenotusingtheoptionalparameterkeyandreverse.Pythonwillautomaticallysorttheitemsinascendingorder. Example: Let’stakeanexampletocheckhowtosortdictionariesinPython dict={6:'George',2:'John',1:'Potter',9:'Micheal',7:'Robert',8:'Gayle'} b=sorted(dict.keys()) print("Sortedkeys",b) c=sorted(dict.items()) print("SortedValues",c) Afterwritingtheabovecode,wehavetosortbothvaluesandkeysavailableinthedictionary.Inpython,offersbuilt-infunctionskeys()anditems()tosortthedictionary.Wecanapplythesefunctioniterableasanargumentandreturnsanewsortedlist. HereistheScreenshotofthefollowinggivencode Pythondictionarysort ThisishowtosortthedictionaryinPython. ReadPythondictionaryappendwithexamples CheckPythondictionarysort–Anotherapproach SupposewehaveadictionaryinPythonthatcontainstheelementsonourfruitmenu.Sonowwewanttosorttheordereddictionaryindescendingorderofvaluesandkeys.Inthisexample,wehavetousethereverseargumentandassignthemvaluesastrue. Example: Let’stakeanexampletocheckhowtosortdictionaryinPythonbyreversemethod dict={"Mangoes":200,"Banana":900,"Cherry":700,"Grapes":400} new_list=sorted(dict.items(),key=lambdax:x[1],reverse=True) foriinnew_list: print(i[0],i[1]) HereistheScreenshotofthefollowinggivencode Pythondictionarysortbyreversemethod ThisishowtosortdictionaryinPython. ReadHowtoconvertdictionarytoJSONinPython Pythondictionarysortbyvalue NowwecanseehowtosortadictionaryvalueinPython.Byusingthesorted()functionyoucansortthevaluesofadictionary.Inthisexamplewecanuseitems()andsorted()functiontosortthevaluesInpythondictionarytherearevariousmethodtosortthevaluesSortinDescendingorderSortinAscendingorder Example: Let’stakeanexampleandcheckhowtosortadictionaryvalueinpythonindescendingorder. dict={"Python":750,"Java":950,"Ruby":700,"C++":200} sort_values=sorted(dict.items(),key=lambday:y[1],reverse=True) foriinsort_values: print(i[0],i[1]) HereistheScreenshotofthefollowinggivencode Pythondictionarysortbyvalue ThisisanexampleofaPythondictionarysortbyvalue. Pythondictionarysortbyvalue–Anotherexample NowwewillcheckhowtosortadictionarybyvalueinPythonusingthesortedfunction. Example: my_dict={"Australia":250,"Germany":950,"France":170,"England":150} new_list=sorted(my_dict.items(),key=lambdax:x[1]) sort_values=dict(new_list) print(sort_values) Intheabovecode,youcancheckthatitreturnsanewsortedlistinascendingorder. HereistheScreenshotofthefollowinggivencode Pythondictionarysortbyvaluesusingthesortedmethod ThisisanexampleofaPythondictionarysortbyvalue. ReadPythonConcatenateDictionary+Examples PythonDictionarysortbykey LetusseehowtosortadictionarykeyinPython.Tosortdictionarykeyinpythonwecanusedict.items()andsorted(iterable)method.Dict.items()methodreturnsanobjectthatstoreskey-valuepairsofdictionaries.Thekey-valuepairsarecontainedastuplesintheobjectoritems.Thesorted(iterable)methodalwaysreturnsthesortedlist.Thismethodsortstheno.ofelementswhichisavailableinthegivendictionary. Example: Let’stakeanexampleandcheckhowtosortadictionarykeyinPython my_dict={"m":250,"o":950,"b":170,"a":150} sort_keys=my_dict.items() new_items=sorted(sort_keys) print(new_items) Intheaboveexample,First,wewillinitializeadictionaryandassignthemakey-valuepairvalue.Thenusedict.items()functiontogetaniterablesequencevalues. HereistheScreenshotofthefollowinggivencode Pythondictionarysortbykey ReadPythonDictionaryupdatewithexamples HowtosortadictionarykeysinPython–Anotherapproach Usingdict.keys()wecansortthedictionarykeysinPython.Thismethodreturnsaniterableviewobjectthatdisplaysallthekeyswhichisavailableinthedictionary. Example: Let’stakeanexampleandcheckhowtosortdictionarykeysinPython my_dict={"p":350,"z":750,"a":170,"c":110} sorted(my_dict.keys()) forkeyinsorted(my_dict.keys()): print(key,":",my_dict[key]) HereistheScreenshotofthefollowinggivencode Pythondictionarysortbykeysmethod ThisishowtosortdictionarykeysinPython. PythondictionarysortbyvalueDescending LetusseehowtosortadictionaryvalueindescendingorderinPython.Usingdict.items()togetaniterableitemthatstoreskey-valuepairsofdictionariesandcallsorted(iterable,key)functionthatreturnsanewsortedlist.Inthiscase,weassignkeyattributesinsortedfunctionasanargumentwithfaslambdakey-valuetosortthevalues. Example: Let’stakeanexampleandcheckhowtosortadictionaryvalueindescendingorder fromtypingimportOrderedDict my_dict={1:{"p":350,"z":750,"a":170,"c":110}, 6:{"p":100,"z":700,"a":120,"c":900}, 4:{"p":300,"z":200,"a":450,"c":130}} sort_values=my_dict.items() new_item=sorted(sort_values,key=lambdakey_value:key_value[1]["c"],reverse=True) list=OrderedDict(new_item) print(list) Intheabovecodefirst,wewillimportanordereddictlibraryandcreateadictionary.Thekey_value[1][inner_key]tosortthepreviousresultiterablebyinnerkeyvalues. HereistheScreenshotofthefollowinggivencode Pythondictionarysortbyvaluedescending ThisishowtosortaPythondictionarybyvalueDescending. ReadPythondictionaryvaluestolist Pythondictionarysortbyvaluealphabetically InPython,adictionaryisformedwithkey-valuepairbythe{key:value}method.Thus,inthemy_dictvariable,thekeysarethenames,andthevaluesaretheintegerstotherightofthenames.Tosortthevaluesalphabeticallyyoucansortandprintthepairsinthedictionarythatwillallhavethesamekeys. Example: Let’stakeanexampleandcheckhowtosortdictionaryvaluesalphabetically. my_dict={'John':2, 'George':3, 'Micheal':4, 'Andrew':6,} forvalueinsorted(my_dict.items(),key=lambdax:x[0],reverse=True): print(value) HereistheScreenshotofthefollowinggivencode Pythondictionarysortbyvaluealphabetically Pythondictionarysortbykeyalphabetically LetusseehowtosortadictionarykeyalphabeticallyinPython.Tosortadictionarykeyalphabeticallywecanusedict.items()andsorted(iterable)function.Inthisexamplewecanuseasimplealgorithmtosortdictionarykeysinalphabeticalorder,First,sortthekeysusingthePythonsorted()function.Thisfunctionsortsthenumberofelementswhichisavailableinthegivendictionary(key-value)pair. Example: new_dict={"z":220,"v":450,"u":120,"t":350} sorted_keys=new_dict.items() new_values=sorted(sorted_keys) print(new_values) HereistheScreenshotofthefollowinggivencode Pythondictionarysortbykeyalphabetically ThisishowtosortaPythondictionarybykeyalphabetically. ReadPythonCheckifavariableisanumber Pythondictionarysortreverse LetusseehowtoreversetheorderofkeysinPythondictionary.Theorderkeysareiteratedinisanarbitraryelement.Toreversethekey-valuepairswecanusedict.keys()functionandloopingmethod. Example: Let’stakeanexampleandcheckhowtoreversetheorderofkeys dict={'l':1,'m':2,'n':3} foriinreversed(list(dict.keys())): print(i) HereistheScreenshotofthefollowinggivencode Pythondictionarysortreverse ThisisanexampleofaPythondictionarysortreverse. HowtoreversetheorderofkeysinPythondictionary Inthisexample,wewillusethecombinationofdictionaryfunctionstoperformthisparticulartask.Byusinglist(),keys(),sorted(),reversed().Itwillsortthekeysandreversedgetsthekeyextractedusingdict.keys()functionindescendingorder. Example: my_dict={2:"John",5:"George",3:"Micheal",2:"James"} new_value=list(reversed(sorted(my_dict.keys()))) print(new_value) HereistheScreenshotofthefollowinggivencode Pythondictionarysortreversekeysmethod ThisishowtoreversetheorderofkeysinaPythondictionary. ReadCheckifNumPyArrayisEmptyinPython Pythondictionarysortbykeyvalue Letusseehowtosortkey-valuepairsusinglambdafunctionalongwiththeitem()andsorted()Lambda()functionsaredefinedwithoutaname,that’swhyitisalsocalledasanonymousfunction.Key-valuepairsareseparatedbycommasandenclosedwithcurlybrackets.Thesorted()functionisusedtosortthekeysofthegivendictionary. Example: Let’stakeanexampleandcheckhowtosortkey-valuepairsinthedictionary. my_dict={3:'George', 5:'Micheal', 4:'John'} sort_values=sorted( my_dict.items(), key=lambdakv:kv[1])#sortkeyandvalues print("Sortedvaluesandkeysis:", sort_values) HereistheScreenshotofthefollowinggivencode Pythondictionarysortbykey-value Thisishowtosortapythondictionarybykeyvalue. Pythondictionarysortwithlambda LetusseehowtosortadictionarywiththelambdafunctioninPython.Pythonlambdafunctionsarefunctionsthatdon’thaveanyname,theyarealsoknownasnamelessfunctions.Thewordlambdaisakeywordthatspecifieswhatfollowersareanonymous.Thebodyofthelambdafunctioniswritteninasingleline.Duetothisreason,Pythonlambdafunctionsareknownasthrowawayfunctions.Theyarealsousedwiththehigher-orderfunctionwhichtakesafunctionasaninputandreturneditasanoutput. Example: Let’stakeanexampleandcheckhowtosortadictionarywithalambdafunction my_dict=[{"Country":"Germany","Val":40}, {"Country":"England","Val":10}, {"Country":"Japan","Val":60}] print(sorted(my_dict,key=lambdai:i['Val'])) print("\r") print(sorted(my_dict,key=lambdai:(i['Val'],i['Country']))) print("\r") print(sorted(my_dict,key=lambdai:i['Val'],reverse=True))#descendingorder Note:Fordescendingorderuse“reverse=True” Intheaboveexample,weareusingsorted()withalambdafunction.First,initializethelistofdictionariesandusingthesortedandlambdafunctiontoprintthelistsortedbythe“Val”attribute.Usingsortedandlambdafunctiontoprintlistsortedby“Val”indescendingorder. HereistheScreenshotofthefollowinggivencode Pythondictionarysortwithlambda ThisishowtosortaPythondictionarywithlambda. ReadPythonremovesubstringfromaString Pythondictionarysortbyalphabetically LetusseehowtosortadictionarybyalphabeticallyinPython.Tosortadictionarybyalphabeticallywecanusesorted()anddict.items()Itwillretuenanewlistintheformofkey-valuepairs. Example: Let’stakeanexampleandcheckhowtosortadictionaryalphabetically my_dict={"k":430,"m":450,"c":420,"a":350} new_alpha=my_dict.items() new_val=sorted(new_alpha) print(new_val) HereistheScreenshotofthefollowinggivencode Pythondictionarysortbyalphabetically Thisishowtosortapythondictionaryalphabetically. Pythondictionarysortbyvaluelist HerewewillcheckhowtosortvalueinthelistinPython.Byusingsorted()anddict.items()functionswewillcheckhowtosortvalueinthelist. Example: my_dict={'u':[4,9,2],'v':[7,1,3],'w':[5,2,8]} sort_list={l:sorted(m)forl,minmy_dict.items()}#sortvaluebylist print(sort_list) HereistheScreenshotofthefollowinggivencode Pythondictionarysortbyvaluelist ThisishowtosortvalueinthelistinPython. Pythonsortdictionarybyvaluethenkey Tosortadictionarybyvaluethenthekeywecaneasilyusethelambdaandsortedfunction.Inthisexample,wecansetthisreverseflagorderastruewhichmeansthevaluewillbeindescendingorder. Example: Let’stakeanexampleandcheckhowtosortadictionarybyvaluethanthekey dict={49:1,52:4,74:3,19:6,101:2} z=sorted(dict.items(),key=lambdax:(x[1],x[0]),reverse=True) print(z) HereistheScreenshotofthefollowinggivencode Pythonsortdictionarybyvaluethenkey ThisishowtosortadictionarybyvaluethenkeyinPython. YoumaylikethefollowingPythontutorials: PythonfindsubstringinstringPython3stringreplace()methodRegistrationforminPythonusingTkinterPdfFileWriterPythonExamples(20examples) InthisPythontutorial,wewilldiscussPythonDictionarysort.HerewewillalsoseethePythoncreatestringexamples: PythondictionarysortbyvaluePythondictionarysortbykeyPythondictionarysortbyvaluedescendingPythondictionarysortbyvaluealphabeticallyPythondictionarysortbykeyalphabeticallyPythondictionarysortreversePythondictionarysortbykeyvaluePythondictionarysortwithlambdaPythondictionarysortbyalphabeticallyPythondictionarysortbyvaluelistPythonsortdictionarybyvaluethenkey BijayKumarEntrepreneur,Founder,Author,Blogger,Trainer,andmore.Checkoutmyprofile. enjoysharepoint.com/ Search FollowusinTwitter&Facebook Follow@PythonGuides RecentPosts PyTorchActivationFunction[WIth11Examples] PythonScipyStatsNorm[14AmazingExamples] PythonScipyNormalTest[WithExamples] PythonScipyMannWhitneyu–HelpfulTutorial PythonScipyStatsPoisson–UsefulGuide



請為這篇文章評分?