How to Sort a Dictionary by Value in Python | Career Karma

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

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by ... Exploreyourtrainingoptionsin10minutes GetMatched X Back BrowseBootcamps PopularBootcamps BestCodingBootcamps BestOnlineBootcamps BestWebDesignBootcamps BestDataScienceBootcamps BestTechnologySalesBootcamps BestDataAnalyticsBootcamps BestCybersecurityBootcamps BestProductManagementBotcamps BestProjectManagementBootcamps BestDigitalMarketingBootcamps BootcampsNearYou NewYork LosAngeles SanFrancisco Atlanta Chicago Seattle SanDiego Houston BrowseAllLocations ExplorebySubject Python WebDevelopment DigitalMarketing iOS Java JavaScript SQL MachineLearning SeeAllSubjects LearnforFree BrowseQuestionsFromOthers Bootcamps101 DataScience SoftwareEngineering Full-StackDevelopment JavaScript JobSearch CareerChanges ViewallCareerDiscussions BrowseTopCareers SoftwareEngineering WebDevelopment MobileAppDevelopment DataScience Cybersecurity ProductManagement DigitalMarketing UX/UIDesign ChoosingaBootcamp WhatisaCodingBootcamp? AreCodingBootcampsWorthIt? HowtoChooseaCodingBootcamp BestOnlineCodingBootcampsandCourses BestFreeBootcampsandCodingTraining CodingBootcampvs.CommunityCollege CodingBootcampvs.Self-Learning Bootcampsvs.Certifications:Compared ReadStoriesfromStudents PayingforaBootcamp HowtoPayforCodingBootcamp UltimateGuidetoCodingBootcampLoans BestCodingBootcampScholarshipsandGrants EducationStipendsforCodingBootcamps GetYourCodingBootcampSponsoredbyYourEmployer GIBillandCodingBootcamps OtherTopicsinTech TechIntevriews CareerAdvice Python HTML CSS JavaScript Git Java C++ Startmyjourney Community CareerGuides Schools&Applications PrepCourses&Scholarships Resources LiveEvents Stories About Company Jobs Values Publication Press ReskillAmerica PartnerWithUs ResourceCenterPythonHowtoSortaDictionarybyValueinPython Facebook Twitter LinkedIn TosortadictionarybyvalueinPythonyoucanusethesorted()function.Python’ssorted()functioncanbeusedtosortdictionariesbykey,whichallowsforacustomsortingmethod.sorted()takesthreearguments:object,key,andreverse. Dictionariesareunordereddatastructures.Theyuseamappingstructuretostoredata.Dictionariesmapkeystovalues,creatingpairsthatholdrelateddata. UsingthePythonsorted()method,youcansortthecontentsofadictionarybyvalue.Forinstance,torankthepopularityofitemsonacoffeemenu,orlistthoseitemsinalphabeticalorder,youcanusePython’ssorted()method.Thistutorialwilldiscusshowthesorted()methodworksandhowyoucanuseittosortthecontentsofadictionary.  Pythonsorted()Refresher Python’sbuilt-insorted()functioncanbeusedtosortiterableobjectsbyakey,suchaslists,tuples,anddictionaries.Thesorted()functionsortstheitemsofthespecifiediterableobjectandcreatesanewobjectwiththenewlysortedvalues. Here’sthesyntaxforthesorted()method: sorted(object,key,reverse) Themethodtakesinthreeparameters: object:theiterableobjectthatyouwanttosort(required)key:thefunctionthatallowsyoutoperformcustomsortoperations(optional)reverse:specifieswhethertheobjectshouldbesortedindescendingorder(optional) Asyoucansee,“object”istheonlyrequiredparameter.Ifyoudecidenottousetheoptional“key”and“reverse”parameters,Pythonwillautomaticallysorttheobjectinascendingorder. 81%ofparticipantsstatedtheyfeltmoreconfidentabouttheirtechjobprospectsafterattendingabootcamp.Getmatchedtoabootcamptoday. FindYourBootcampMatch Theaveragebootcampgradspentlessthansixmonthsincareertransition,fromstartingabootcamptofindingtheirfirstjob. Startyourcareerswitchtoday Note:CareerKarmawroteafullguideonthesort()andsorted()methodsinPython.Ifyou’relookingtolearnmoreaboutthismethodandthekeyparameter,checkoutourPythonsort()tutorial. Let’swalkthroughaquickexampletoillustratehowthesorted()methodworks.  »MORE: Node.jsvsPython:DifferencesandSimilaritiesSaythatweareoperatingacoffeeshopandwewanttoretrieveanalphabeticallistofourCoffeeClub(loyalty)customers.Wealreadyhavealistofcustomers,butitisorderedbysign-update.Wecouldusethefollowingcodetosortourlist: customers=['KaleyFernandez','DariusRowland','IsaacBorthwick','AlexandriaKidd'] sorted_customers=sorted(customers) print(sorted_customers) Ourcodesortsthecustomersarrayandreturnsthefollowing: ['AlexandriaKidd','DariusRowland','IsaacBorthwick','KaleyFernandez'] Onthefirstlineofourcode,wedeclarealistthatstoresourcustomers’names;thislistiscalled:customers.Then,weusethesorted()methodtosortthelistofcustomernamesinascendingorder;thisnewlistiscalled:sorted_customers.Finally,weprintoutthenewlysortedlisttotheconsoleusingtheprint()function. SortaDictionarybyValue Let’ssaythatyouhaveadictionaryandyouwanttosortitbykey-valuepairs.Youcandothisbyusingtwofunctionstogether:items()andsorted().  FindYourBootcampMatch CareerKarmamatchesyouwithtoptechbootcamps Accessexclusivescholarshipsandprepcourses Selectyourinterest SoftwareEngineering Design DataScience DataAnalytics Sales UXDesign CyberSecurity DigitalMarketing Firstname Lastname Email Phonenumber BycontinuingyouagreetoourTermsofServiceandPrivacyPolicy,andyouconsenttoreceiveoffersandopportunitiesfromCareerKarmabytelephone,textmessage,andemail. Theitems()functionallowsyoutoretrievetheitemsinadictionary.Wecanusethisfunctionincombinationwiththesorted()functionandacustomkeyparametertosortadictionarybyvalue.Considerthefollowingtwoexamples. Example1:SortinDescendingOrder Let’sreturntothecoffeeshop.Supposewehaveadictionarythatstorestheitemsonourcoffeemenuaswellashowmanyofeachitemwereorderedinthelastmonth.Wewanttoseewhatthemostpopularcoffeewaslastmonth,sowedecidetosorttheorderdictionaryindescendingorderofvalues. Here’saprogramwecouldusetosortthecontentsofourdictionarybyvalue: orders={ 'cappuccino':54, 'latte':56, 'espresso':72, 'americano':48, 'cortado':41 } sort_orders=sorted(orders.items(),key=lambdax:x[1],reverse=True) foriinsort_orders: print(i[0],i[1]) Ourcodereturnsthefollowing: »MORE: PythonModuleNotFoundErrorSolutionespresso72 latte56 cappuccino54 americano48 cortado41 There’salotgoingoninourcode,solet’sbreakitdown.  Atthestartofourcode,wedefineadictionarycalledordersthatstoresthenamesofcoffeesaskeysandthenumbersoldasvalues. "CareerKarmaenteredmylifewhenIneededitmostandquicklyhelpedmematchwithabootcamp.Twomonthsaftergraduating,Ifoundmydreamjobthatalignedwithmyvaluesandgoalsinlife!" Venus,SoftwareEngineeratRockbot FindYourBootcampMatch Then,weusethesorted()methodtosorttheordersdictionarybyvalue.Here’sabreakdownofhowweusedthesorted()method: ParameterTextDescriptionobjectorders.items() Referstoallvaluesinour“orders”dictionary.Ifweweretousejust“orders”,wewouldhavetoreferencetheindexpositionoftheitemtogetitsindividualvalue.Whereasifweuseorders.items(),aniterablelistwiththeitemsinalistiscreated.keykey=lambdax:x[1]Asortingmechanismthatallowsustosortourdictionarybyvalue.ThisisanexampleofaLambdafunction,whichisafunctionwithoutaname.reversereverse=TrueStatesthatwewantourdatatobesortedindescendingorder. Finally,wecreateaforloopthatloopsthrougheachitemcreatedinoursort_ordermethodandprintsoutbothitskeynameanditsvalue,sortedintheorderwespecifiedinthesort_orderfunction. Example2:SortinAscendingOrder Similarly,ifwewantedtofindouttheleastpopulardrinksoldatourcoffeeshop,wecouldusethesamecodeasabovebutwithoutthereverse=Trueparameter.Here’sanexampleofthecodeforthis: orders={ 'cappuccino':54, 'latte':56, 'espresso':72, 'americano':48, 'cortado':41 } sort_orders=sorted(orders.items(),key=lambdax:x[1]) foriinsort_orders: print(i[0],i[1]) Whenwerunourcode,thefollowingvaluesarereturned: cortado41 americano48 cappuccino54 latte56 espresso72 Asyoucansee,ourcodereturnedalistofitemsarrangedinascendingorder,basedonthenumberofeachitemorderedinthelastmonth. »MORE: PythonCollections:AStep-By-StepGuideListComprehension Inaddition,wecanuselistcomprehensiontosortdictionarycontentsbyvalue.ListcomprehensionisaconcisetechniquetocreatelistsinPythonandcansavespaceifyouarecreatingmorecomplexsortmethods. Here’sthecodewewouldusetosortourcoffeeordersinascendingorderbythenumberofeachcoffeethatwasorderedusinglistcomprehension: orders={ 'cappuccino':54, 'latte':56, 'espresso':72, 'americano':48, 'cortado':41 } [print(key,value)for(key,value)insorted(orders.items(),key=lambdax:x[1]) Whenwerunourcode,thefollowingresponseisreturned: cortado41 americano48 cappuccino54 latte56 espresso72 Theresultofourcodewasthesameasouraboveexamplewherewesortedthecontentsoftheorderslistinascendingorder.Butinsteadofdefiningasort_ordersvariableandcreatingaseparateforlooptoiteratethroughthesortedlist,wecreatedalistusingthelistcomprehensiontechnique. Thelistcomprehensionwecreatedabovesortsthrougheachiteminourlistinascendingorder,thenprintsoutthekeyandvalueofeachdictionaryitemtotheconsole. Conclusion Whenyou’reworkingwithdictionariesinPython,sortingadictionarybyvalueisacommonoperation.Thesorted()methodallowsyoutosortasetofdatabasedonyourneeds. Thistutorialdiscussed,providingexamples,howtousethesorted()methodtosortadictionarybyvalueinPython,includinghowtousethekeyandreverseparameters.  Nowyou’rereadytostartsortingdictionariesbyvaluelikeaPythonpro! 5Ratings Aboutus:CareerKarmaisaplatformdesignedtohelpjobseekersfind,research,andconnectwithjobtrainingprogramstoadvancetheircareers.LearnabouttheCKpublication. What'sNext? Wanttotakeaction? Getmatchedwithtopbootcamps Wanttodivedeeper? Askaquestiontoourcommunity Wanttoexploretechcareers? Takeourcareersquiz JamesGallagher JamesGallagherisaself-taughtprogrammerandthetechnicalcontentmanageratCareerKarma.HehasexperienceinrangeofprogramminglanguagesandextensiveexpertiseinPython,HTML,CSS,andJavaScript.Jameshaswrittenhundredsofprogrammingtutorials,andhefrequentlycontributestopublicationslikeCodecademy,Treehouse,Repl.it,Afrotech,andothers.He...readmore ReadmorebyJamesGallagher ShareThis PreviousArticleHowtoCodetheFibonacciSequenceinPython NextArticlePython'str'objectdoesnotsupportitemassignmentsolution Jul28,2020 Comments(1) Yokisays: Jun16,2020at3:30pm Thanksfortheexplanation,ithelpedmetosolvemyassignment!! Reply LeaveaReplyCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*YourCommentName* Email* Website Δ ApplytotoptechtrainingprogramsinoneclickGetMatched RelatedArticles Python Python Python Python Manycareersintechpayover$100,000peryear.WithhelpfromCareerKarma,youcanfindatrainingprogramthatmeetsyourneedsandwillsetyouupforalong-term,well-paidcareerintech. Selectyourinterest: SoftwareEngineering Design DataScience DataAnalytics Sales CyberSecurity DigitalMarketing FirstName LastName Email PhoneNumber GETMATCHED Findtherightbootcampforyou BycontinuingyouagreetoourTermsofServiceandPrivacyPolicy,andyouconsenttoreceiveoffersandopportunitiesfromCareerKarmabytelephone,textmessage,andemail. X Findatop-ratedtrainingprogram



請為這篇文章評分?