Python: Sort a Dictionary by Values - datagy

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

Sort a Python Dictionary by Values Using dict.items and Sorted ... The Python sorted() function allows us to, well, sort an item. The sorted() ... Python:SortaDictionarybyValuesNovember19,2021March8,2022 Inthistutorial,you’lllearnhowtousePythontosortadictionarybytheirvalues.BeginninginPython3.7,dictionariesbecameordered. Sortingadictionarycanhavetremendousbenefits.Sayyou’restoringyourclients’informationbyname.Sortingthedatareducesitscomplexitytremendously,makingthedataeasiertoworkwith. TheQuickAnswer:Usedict.items()andsorted() TableofContents WhySortaPythonDictionarySortaPythonDictionarybyValuesUsingdict.itemsandSortedSortaPythonDictionarybyValuesUsingaForLoopSortaPythonDictionarybyValuesUsingaDictionaryComprehensionConclusion WhySortaPythonDictionary Pythondictionariesareincrediblyusefuldatastructures.Theystoreddatainkey:valuepairs,allowingustoretrievedataveryeasily.BeginninginPython3.7,Pythondictionariesbecomeordered,meaningthattheirordercanbechangedtoimproveefficiency. Sortingadictionarybythekey’svaluescanhelpinefficiencyifyou’refrequentlyidentifyingkeyswitheithermaximumorminimumvalues.Sayyou’rekeepingtrackofplayers’scoresandneedtoaccesstheplayerswiththehighestandlowestscoresmorefrequently.Sortingyourdictionary,then,becomesatoolthatallowsyoutooptimizeretrieval. NeedtocheckifakeyexistsinaPythondictionary?Checkoutthistutorial,whichteachesyoufivedifferentwaysofseeingifakeyexistsinaPythondictionary,includinghowtoreturnadefaultvalue. SortaPythonDictionarybyValuesUsingdict.itemsandSorted ThePythonsorted()functionallowsusto,well,sortanitem.Thesorted()functionacceptsthreeparameters: iterable:Anitemtosortkey:Thekeytosortbyreverse:Whethertosortinreverseorderornot Thekeyisthemethodbywhichtosortdata.Inessence,it’safunctionthat’sevaluatedinordertocompareagainsthowtosort. Becausewewanttocompareagainsttheitems’values,wewillusekey=item.get,whichreturnsakey’svalue. Let’sseewhatthislookslikeinpractice: #SortingaDictionarybyitsvaluesusingsorted() sales={ 'apples':12, 'bananas':32, 'oranges':24, 'grapes':43, 'tangerines':55 } sorted=sorted(sales,key=sales.get) sorted_dict={} forkeyinsorted: sorted_dict[key]=sales[key] print(sorted_dict) #Returns:{'apples':12,'oranges':24,'bananas':32,'grapes':43,'tangerines':55} Let’stakealookatwhatwe’vedonehere.Wegeneratedalist,usingthesorted()functionthatreturnsthevaluesinascendingorder.Wethenloopedoverthegeneratednewkey:pairvaluesinournewdictionarysorted_dict. Wecanalsoskipthestepoffirstcreatingthelistandthenloopingoveritbyusingaslightlytweakedreverse()function.Let’sseehowwecantrimthisdown: #SortingaDictionarybyitsvaluesusingsorted() sales={ 'apples':12, 'bananas':32, 'oranges':24, 'grapes':43, 'tangerines':55 } sorted=dict(sorted(sales.items(),key=lambdax:x[1])) print(sorted) #Returns:{'apples':12,'oranges':24,'bananas':32,'grapes':43,'tangerines':55} Inthisexample,we’vecutoutadecentamountofcode.Let’sbreakthisdownabit: Wepassinthesales.items(),whichreturnstuplesofkey:valuepairsWethenusethelambdafunctionthatgrabstheseconditeminthepair(thevalue)Wefinallyturnthisbackintoadictionaryusingthedict()function Ifwewantedtosortthevaluesindescendingorder,youcouldalsopassinthereverse=Trueargument. Inthenextsection,you’lllearnhowtouseaPythonforlooptosortadictionarybyitsvalues. CheckoutsomeotherPythontutorialsondatagy,includingourcompleteguidetostylingPandasandourcomprehensiveoverviewofPivotTablesinPandas! SortaPythonDictionarybyValuesUsingaForLoop Inthissection,you’lllearnhowtouseaPythonforlooptosortadictionarybyitsvalues. We’llusethePythonreverse()functionagainandloopovertheresultinglistoftuples.We’llthenassignnewkey:pairvaluestoadictionarythatwillstoreoursorteddictionary. Let’sseehowwecandothisinPython: #SortingaDictionarybyitsvaluesusingsorted()andaforloop sales={ 'apples':12, 'bananas':32, 'oranges':24, 'grapes':43, 'tangerines':55 } sorted_dict={} forkey,valueinsorted(sales.items(),key=lambdax:x[1]): sorted_dict[key]=value print(sorted_dict) #Returns:{'apples':12,'oranges':24,'bananas':32,'grapes':43,'tangerines':55} Here,weloopoverthegeneratedlistoftuples,includingbothitskeysandvalues.Wethenassignthekeyandvaluepairtothenewdictionary. Inthenextsection,you’lllearnhowtosortadictionarybyitsvaluesusingaPythonlistcomprehension. WanttolearnmoreaboutPythonfor-loops?Checkoutmyin-depthtutorialthattakesyourfrombeginnertoadvancedfor-loopsuser!Wanttowatchavideoinstead?CheckoutmyYouTubetutorialhere. SortaPythonDictionarybyValuesUsingaDictionaryComprehension Wecanturntheaboveforloopintoadictionarycomprehension,whichcutsdowntheamountofcodeweneedtowrite.Infact,turningthisintoadictionarycomprehensionmakestheentirecodemorereadable. Newtodictionarycomprehensions?Checkoutmyin-depthtutorialonthemhere,whichcoversoffeverythingyouneedtoknow. Theimagebelowprovidesaneasy-to-readoverviewofPythondictionarycomprehensions: Let’sseehowwecanuseaPythondictionarycomprehensiontosortadictionarybyitsvalues: #SortingaDictionarybyitsvaluesusingsorted()andadictionarycomprehension sales={ 'apples':12, 'bananas':32, 'oranges':24, 'grapes':43, 'tangerines':55 } sorted_dict={key:valueforkey,valueinsorted(sales.items(),key=lambdax:x[1])} print(sorted_dict) #Returns:{'apples':12,'oranges':24,'bananas':32,'grapes':43,'tangerines':55} WanttolearnmoreaboutPythonlistcomprehensions?Checkoutthisin-depthtutorialthatcoversoffeverythingyouneedtoknow,withhands-onexamples.Moreofavisuallearner,checkoutmyYouTubetutorialhere. Conclusion Inthistutorial,youlearnedhowtosortaPythondictionarybyitsvalues.Youlearnedhowtodothisusingthedict.items()method,aPythonforloop,alistcomprehension,andalambdafunction. TolearnmoreaboutPythondictionaries,checkouttheofficialdocumentationhere. Tags:PythonPythonDictionariespreviousPythonMergeDictionaries–CombineDictionaries(7Ways)next4WaystoClearaPythonList 1thoughton“Python:SortaDictionarybyValues” Pingback: PythonDictionaries:ACompleteOverview•datagy LeaveaReplyCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*Name* Email* Website Comment*Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. LearnPythonin30Daysforfree LearnMore Getthefreecoursedeliveredtoyourinbox,everyday–for30days! Youcanunsubscribeanytime. PrivacyPolicy. LearnPython Loading... Thankyou! You'llgetyourfirstlessonshortly! Heythere,I'mNik! datagy.ioisasitethatmakeslearningPythonanddatascienceeasy.Learnmoreaboutdatagyhere. DownloadYourFREEPandasGuide! GetyourFREEdownloadnow!



請為這篇文章評分?