python - How do I sort a dictionary by value? - Stack Overflow

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

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore HowdoIsortadictionarybyvalue? AskQuestion Asked 13years,5monthsago Modified 9monthsago Viewed 4.5mtimes 3416 1496 Thisquestion'sanswersareacommunityeffort.Editexistinganswerstoimprovethispost.Itisnotcurrentlyacceptingnewanswersorinteractions. Ihaveadictionaryofvaluesreadfromtwofieldsinadatabase:astringfieldandanumericfield.Thestringfieldisunique,sothatisthekeyofthedictionary. Icansortonthekeys,buthowcanIsortbasedonthevalues? Note:IhavereadStackOverflowquestionhereHowdoIsortalistofdictionariesbyavalueofthedictionary?andprobablycouldchangemycodetohavealistofdictionaries,butsinceIdonotreallyneedalistofdictionariesIwantedtoknowifthereisasimplersolutiontosorteitherinascendingordescendingorder. pythonsortingdictionary Share Follow editedMar20,2019at22:50 Anvesh 6111silverbadge99bronzebadges askedMar5,2009at0:49 GernBlanstonGernBlanston 42.2k1919goldbadges4848silverbadges6464bronzebadges 5 9 Thedictionarydatastructuredoesnothaveinherentorder.Youcaniteratethroughitbutthere'snothingtoguaranteethattheiterationwillfollowanyparticularorder.Thisisbydesign,soyourbestbetisprobalyusinganohterdatastructureforrepresentation. – Daishiman Jul5,2010at2:08 135 "sorted()"canoperateondictionaries(andreturnsalistofsortedkeys),soIthinkhe'sawareofthis.Withoutknowinghisprogram,it'sabsurdtotellsomeonethey'reusingthewrongdatastructure.Iffastlookupsarewhatyouneed90%ofthetime,thenadictisprobablywhatyouwant. – bobpaul Feb15,2013at19:04 Allthreeoutputs(keys,values,both)forsortingdictionariesarecoveredhereinaclearandconcisestyle:stackoverflow.com/questions/16772071/sort-dict-by-value-python – JStrahl Mar7,2016at10:14 2 @DaishimanThebaseclassmightnotbeorderedbutOrderedDictisofcourse. – TaylorD.Edmiston Sep9,2017at1:10 1 InPython3.6+dictionariespreserveinsertionorder.Thisis,ofcourse,notthesameaspossibilityofsortingthembyvalue,butontheotherhanditisnolongervalidtosaythat"dictionarydatastructuredoesnothaveinherentorder". – KonradKocik Dec31,2018at13:30 Commentsdisabledondeleted/lockedposts/reviews  |  34Answers 34 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 1 2 Next 6470 +500 Python3.7+orCPython3.6 DictspreserveinsertionorderinPython3.7+.SameinCPython3.6,butit'sanimplementationdetail. >>>x={1:2,3:4,4:3,2:1,0:0} >>>{k:vfork,vinsorted(x.items(),key=lambdaitem:item[1])} {0:0,2:1,1:2,4:3,3:4} or >>>dict(sorted(x.items(),key=lambdaitem:item[1])) {0:0,2:1,1:2,4:3,3:4} OlderPython Itisnotpossibletosortadictionary,onlytogetarepresentationofadictionarythatissorted.Dictionariesareinherentlyorderless,butothertypes,suchaslistsandtuples,arenot.Soyouneedanordereddatatypetorepresentsortedvalues,whichwillbealist—probablyalistoftuples. Forinstance, importoperator x={1:2,3:4,4:3,2:1,0:0} sorted_x=sorted(x.items(),key=operator.itemgetter(1)) sorted_xwillbealistoftuplessortedbythesecondelementineachtuple.dict(sorted_x)==x. Andforthosewishingtosortonkeysinsteadofvalues: importoperator x={1:2,3:4,4:3,2:1,0:0} sorted_x=sorted(x.items(),key=operator.itemgetter(0)) InPython3sinceunpackingisnotallowedwecanuse x={1:2,3:4,4:3,2:1,0:0} sorted_x=sorted(x.items(),key=lambdakv:kv[1]) Ifyouwanttheoutputasadict,youcanusecollections.OrderedDict: importcollections sorted_dict=collections.OrderedDict(sorted_x) Share Improvethisanswer Follow editedNov22,2020at19:29 wjandrea 23.8k88goldbadges5151silverbadges7070bronzebadges answeredMar5,2009at0:59 DevinJeanpierreDevinJeanpierre 88.8k44goldbadges5454silverbadges7979bronzebadges 10 48 fortimingsonvariousdictionarysortingbyvalueschemes:writeonly.wordpress.com/2008/08/30/… – GreggLind Mar14,2009at17:55 191 sorted_x.reverse()willgiveyouadescendingordering(bythesecondtupleelement) – saidimuapale May3,2010at5:24 488 saidimu:Sincewe'realreadyusingsorted(),it'smuchmoreefficienttopassinthereverse=Trueargument. – rmh Jul5,2010at2:59 127 Inpython3Iusedalambda:sorted(d.items(),key=lambdax:x[1]).Willthisworkinpython2.x? – Benbob Feb15,2011at15:05 4 WherecanIreadmoreabouttheusageofkey=lambdaitem:item[1]please?ThepartIdon'tquiteunderstandistheitem[1],isitbecausewhenwedox.items()itreturnsthekey-valuepairsandwiththiswecantapintothevaluebydoingitem[1]? – UdonN00dle Nov6,2021at23:56  |  Show5morecomments 1543 Assimpleas:sorted(dict1,key=dict1.get) Well,itisactuallypossibletodoa"sortbydictionaryvalues".RecentlyIhadtodothatinaCodeGolf(StackOverflowquestionCodegolf:Wordfrequencychart).Abridged,theproblemwasofthekind:givenatext,counthowofteneachwordisencounteredanddisplayalistofthetopwords,sortedbydecreasingfrequency. Ifyouconstructadictionarywiththewordsaskeysandthenumberofoccurrencesofeachwordasvalue,simplifiedhereas: fromcollectionsimportdefaultdict d=defaultdict(int) forwintext.split(): d[w]+=1 thenyoucangetalistofthewords,orderedbyfrequencyofusewithsorted(d,key=d.get)-thesortiteratesoverthedictionarykeys,usingthenumberofwordoccurrencesasasortkey. forwinsorted(d,key=d.get,reverse=True): print(w,d[w]) Iamwritingthisdetailedexplanationtoillustratewhatpeopleoftenmeanby"Icaneasilysortadictionarybykey,buthowdoIsortbyvalue"-andIthinktheoriginalpostwastryingtoaddresssuchanissue.Andthesolutionistodosortoflistofthekeys,basedonthevalues,asshownabove. Share Improvethisanswer Follow editedMar10,2020at14:42 BorisVerkhovskiy 11.4k77goldbadges8282silverbadges8080bronzebadges answeredJul5,2010at8:01 NasBanovNasBanov 27.5k66goldbadges4545silverbadges6767bronzebadges 3 38 Thisisalsogoodbutkey=operator.itemgetter(1)shouldbemorescalableforefficiencythankey=d.get – smci Dec9,2011at21:18 12 @blisorted_keys=sorted(d.items(),key=itemgetter(1),reverse=True)andforkey,valinsorted_keys:print"%s:%d"%(key,val)-itemgettercreatesafunctionwhenit'scalled,youdon'tuseitdirectlylikeinyourexample.Andaplainiterationonadictusesthekeyswithoutthevalues – Izkata Aug19,2014at20:21 28 ihavecomefromthefuturetotellyouofcollections.Counter,whichhasamost_commonmethodthatmightinterestyou:) – Eevee Jun25,2017at20:47 Addacomment  |  1087 Youcoulduse: sorted(d.items(),key=lambdax:x[1]) Thiswillsortthedictionarybythevaluesofeachentrywithinthedictionaryfromsmallesttolargest. Tosortitindescendingorderjustaddreverse=True: sorted(d.items(),key=lambdax:x[1],reverse=True) Input: d={'one':1,'three':3,'five':5,'two':2,'four':4} a=sorted(d.items(),key=lambdax:x[1]) print(a) Output: [('one',1),('two',2),('three',3),('four',4),('five',5)] Share Improvethisanswer Follow editedJan10,2020at9:43 Suresh2692 3,60333goldbadges1515silverbadges2525bronzebadges answeredFeb13,2010at16:33 MarkMark 10.9k11goldbadge1414silverbadges55bronzebadges 6 FromwhatI'veseen(docs.python.org/2/library/…),thereisaclasscalledOrderedDictwhichcanbesortedandretainorderwhilststillbeingadictionary.Fromthecodeexamples,youcanuselambdatosortit,butIhaven'ttrieditoutpersonally:P – UsAndRufus Feb20,2013at10:38 70 I'dpreferkey=lambda(k,v):vpersonally – Claudiu Apr9,2015at23:08 @Keyoshouldn'tthatbeitreturnsanorderedlistofkeys(sortedbyvalues)not(k,v)tuples?That'swhatIgetwithPython2.7.10.@Nyxynyxaddtheparameterreverse=Truetosortindescendingorder. – dhj Nov16,2015at16:49 48 @ClaudiuIlikethat(k,v)syntaxtoo,butit'snotavailableinPython3wheretupleparameterunpackingwasremoved. – BobStein Feb5,2016at17:53 1 IfyouwrapthisinanOrderedDict()instanceyouwillgeta(ordered)dictinsteadoflistoftuples! – tsveti_iko Mar21,2019at10:30  |  Show1morecomment 261 Dictscan'tbesorted,butyoucanbuildasortedlistfromthem. Asortedlistofdictvalues: sorted(d.values()) Alistof(key,value)pairs,sortedbyvalue: fromoperatorimportitemgetter sorted(d.items(),key=itemgetter(1)) Share Improvethisanswer Follow editedSep16,2014at17:26 answeredMar5,2009at1:05 RobertoBonvalletRobertoBonvallet 30.1k55goldbadges3838silverbadges5757bronzebadges 3 Whatorderarekeyswiththesamevalueplacedin?Isortedthelistbykeysfirst,thenbyvalues,buttheorderofthekeyswiththesamevaluedoesnotremain. – SabreWolfy Jun18,2012at10:04 7 Dictscannowbesorted,startingwithCPython3.6andallotherPythonimplementationsstartingwith3.7 – BorisVerkhovskiy Apr24,2020at19:38 Trueatthetime,butnowpythondictionariespreservetheorderinwhichitemswereinsertedalreadybydefault.Andthereforetheycanbesorted. – c8999c3f964f64 Mar11at8:21 Addacomment  |  180 InrecentPython2.7,wehavethenewOrderedDicttype,whichrememberstheorderinwhichtheitemswereadded. >>>d={"third":3,"first":1,"fourth":4,"second":2} >>>fork,vind.items(): ...print"%s:%s"%(k,v) ... second:2 fourth:4 third:3 first:1 >>>d {'second':2,'fourth':4,'third':3,'first':1} Tomakeanewordereddictionaryfromtheoriginal,sortingbythevalues: >>>fromcollectionsimportOrderedDict >>>d_sorted_by_value=OrderedDict(sorted(d.items(),key=lambdax:x[1])) TheOrderedDictbehaveslikeanormaldict: >>>fork,vind_sorted_by_value.items(): ...print"%s:%s"%(k,v) ... first:1 second:2 third:3 fourth:4 >>>d_sorted_by_value OrderedDict([('first':1),('second':2),('third':3),('fourth':4)]) Share Improvethisanswer Follow editedApr3,2014at16:59 PeterMortensen 30.2k2121goldbadges100100silverbadges124124bronzebadges answeredJul5,2010at2:50 mykhalmykhal 18.4k1111goldbadges7171silverbadges7878bronzebadges 7 6 Thisisnotwhatthequestionisabout-itisnotaboutmaintainingorderofkeysbutabout"sortingbyvalue" – NasBanov Jul5,2010at7:07 10 @NasBanov:itisNOTsortingbythekey.itissortingintheorder,wecreatetheitems.inourcase,wesortbythevalue.unfortunately,the3-itemdictwasunfortunatelychosensotheorderwasthesame,whensortedvothbyvalueandkey,soiexpandedthesampledict. – mykhal Jul5,2010at10:56 sorted(d.items(),key=lambdax:x[1])Canyouexplainwhatthexmeans,whyitcantakex[1]tolambda?Whydoesitcan'tbex[0]?Thankyouverymuch! – JZAU Nov8,2013at5:12 1 @Boernd.items()returnsalist-likecontainerof(key,value)tuples.[0]accessesthefirstelementofthetuple--thekey--and[1]accessesthesecondelement--thevalue. – BallpointBen Apr10,2018at14:29 2 Note:Asof3.6(asaCPython/PyPyimplementationdetail)andasof3.7(asaPythonlanguageguarantee),plaindictisinsertionorderedaswell,soyoucanjustreplaceOrderedDictwithdictforcoderunningonmodernPython.OrderedDictisn'treallyneededanymoreunlessyouneedtorearrangetheorderofanexistingdict(withmove_to_end/popitem)orneedequalitycomparisonstobeorder-sensitive.Itusesalotmorememorythanplaindict,soifyoucan,dictisthewaytogo. – ShadowRanger Sep4,2019at13:09  |  Show2morecomments 120 UPDATE:5DECEMBER2015usingPython3.5 WhilstIfoundtheacceptedansweruseful,Iwasalsosurprisedthatithasn'tbeenupdatedtoreferenceOrderedDictfromthestandardlibrarycollectionsmoduleasaviable,modernalternative-designedtosolveexactlythistypeofproblem. fromoperatorimportitemgetter fromcollectionsimportOrderedDict x={1:2,3:4,4:3,2:1,0:0} sorted_x=OrderedDict(sorted(x.items(),key=itemgetter(1))) #OrderedDict([(0,0),(2,1),(1,2),(4,3),(3,4)]) TheofficialOrderedDictdocumentationoffersaverysimilarexampletoo,butusingalambdaforthesortfunction: #regularunsorteddictionary d={'banana':3,'apple':4,'pear':1,'orange':2} #dictionarysortedbyvalue OrderedDict(sorted(d.items(),key=lambdat:t[1])) #OrderedDict([('pear',1),('orange',2),('banana',3),('apple',4)]) Share Improvethisanswer Follow editedDec15,2015at5:54 answeredDec5,2015at9:46 arcseldonarcseldon 33.1k1515goldbadges116116silverbadges120120bronzebadges 1 canyouexplainwhatitemgetterdoesinthisexample?otherwisethisseemsjustascrypticasusingalamba – c8999c3f964f64 Mar11at8:29 Addacomment  |  110 PrettymuchthesameasHankGay'sanswer: sorted([(value,key)for(key,value)inmydict.items()]) OroptimizedslightlyassuggestedbyJohnFouhy: sorted((value,key)for(key,value)inmydict.items()) Share Improvethisanswer Follow editedMar12,2019at5:18 JustinBatch 1755bronzebadges answeredMar5,2009at1:06 user26294user26294 5,16733goldbadges2121silverbadges1818bronzebadges 4 10 ..andaswithHankGay'sanswer,youdon'tneedthesquarebrackets.sorted()willhappilytakeanyiterable,suchasageneratorexpression. – JohnFouhy Mar5,2009at1:45 Youmaystillneedtoswapthe(value,key)tupleelementstoendupwiththe(key,value).Anotherlistcomprehensionisthenneeded.[(key,value)for(value,key)insorted_list_of_tuples] – saidimuapale May3,2010at5:22 2 no,it'sbettertoleavesquarebrackets,becausesortedwillhavetorebuildthelistanyway,andrebuildingfromgencompwillbefaster.Goodforcodegolfing,badforspeed.Keeptheugly([])version. – Jean-FrançoisFabre ♦ Dec7,2017at21:21 I'mconfused,thisreturnsanarrayoftuplesnotadict.IMOyouaremissingthedictcomprehensionpart:{x:vforx,vinsorted((value,key)for(key,value)inmydict.items())} – melMass Jun17at12:15 Addacomment  |  85 AsofPython3.6thebuilt-indictwillbeordered Goodnews,sotheOP'soriginalusecaseofmappingpairsretrievedfromadatabasewithuniquestringidsaskeysandnumericvaluesasvaluesintoabuilt-inPythonv3.6+dict,shouldnowrespecttheinsertorder. Ifsaytheresultingtwocolumntableexpressionsfromadatabasequerylike: SELECTa_key,a_valueFROMa_tableORDERBYa_value; wouldbestoredintwoPythontuples,k_seqandv_seq(alignedbynumericalindexandwiththesamelengthofcourse),then: k_seq=('foo','bar','baz') v_seq=(0,1,42) ordered_map=dict(zip(k_seq,v_seq)) Allowtooutputlateras: fork,vinordered_map.items(): print(k,v) yieldinginthiscase(forthenewPython3.6+built-indict!): foo0 bar1 baz42 inthesameorderingpervalueofv. WhereinthePython3.5installonmymachineitcurrentlyyields: bar1 foo0 baz42 Details: Asproposedin2012byRaymondHettinger(cf.mailonpython-devwithsubject"Morecompactdictionarieswithfasteriteration")andnow(in2016)announcedinamailbyVictorStinnertopython-devwithsubject"Python3.6dictbecomescompactandgetsaprivateversion;andkeywordsbecomeordered"duetothefix/implementationofissue27350"Compactandordereddict"inPython3.6wewillnowbeable,touseabuilt-indicttomaintaininsertorder!! HopefullythiswillleadtoathinlayerOrderedDictimplementationasafirststep.As@JimFasarakis-Hilliardindicated,someseeusecasesfortheOrderedDicttypealsointhefuture.IthinkthePythoncommunityatlargewillcarefullyinspect,ifthiswillstandthetestoftime,andwhatthenextstepswillbe. Timetorethinkourcodinghabitstonotmissthepossibilitiesopenedbystableorderingof: Keywordargumentsand (intermediate)dictstorage Thefirstbecauseiteasesdispatchintheimplementationoffunctionsandmethodsinsomecases. Thesecondasitencouragestomoreeasilyusedictsasintermediatestorageinprocessingpipelines. RaymondHettingerkindlyprovideddocumentationexplaining"TheTechBehindPython3.6Dictionaries"-fromhisSanFranciscoPythonMeetupGrouppresentation2016-DEC-08. AndmaybequitesomeStackOverflowhighdecoratedquestionandanswerpageswillreceivevariantsofthisinformationandmanyhighqualityanswerswillrequireaperversionupdatetoo. CaveatEmptor(butalsoseebelowupdate2017-12-15): As@ajcrrightfullynotes:"Theorder-preservingaspectofthisnewimplementationisconsideredanimplementationdetailandshouldnotbereliedupon."(fromthewhatsnew36)notnitpicking,butthecitationwascutabitpessimistic;-).Itcontinuesas"(thismaychangeinthefuture,butitisdesiredtohavethisnewdictimplementationinthelanguageforafewreleasesbeforechangingthelanguagespectomandateorder-preservingsemanticsforallcurrentandfuturePythonimplementations;thisalsohelpspreservebackwards-compatibilitywitholderversionsofthelanguagewhererandomiterationorderisstillineffect,e.g.Python3.5)." Soasinsomehumanlanguages(e.g.German),usageshapesthelanguage,andthewillnowhasbeendeclared...inwhatsnew36. Update2017-12-15: Inamailtothepython-devlist,GuidovanRossumdeclared: Makeitso."Dictkeepsinsertionorder"istheruling.Thanks! So,theversion3.6CPythonside-effectofdictinsertionorderingisnowbecomingpartofthelanguagespec(andnotanymoreonlyanimplementationdetail).Thatmailthreadalsosurfacedsomedistinguishingdesigngoalsforcollections.OrderedDictasremindedbyRaymondHettingerduringdiscussion. Share Improvethisanswer Follow editedDec16,2017at15:47 answeredSep10,2016at10:05 DilettantDilettant 3,15933goldbadges2929silverbadges2828bronzebadges 3 @ajcrthanksforthecaveat,veryappreciated-assmileysandmaybe'swereweavedintomyresponse,theseshouldindicated,thechangeismassivebutofcourse,onlyavailableforCPython(referenceimplementation)andPyPy.Forsomethingcompletelydifferent...Irarelytalktonon-implementationdetailswhencodingman-machineinstructions.IfitwouldonlyhavebeenJython;-)...Imightnothavehadthecouragetowriteit. – Dilettant Sep10,2016at20:22 OrderedDictdefinitelywon'tbedropped;instead,itwillbecomeathinwrapperaroundthecurrentdictimplementation(soyoumightaddthatitwillbecomemorecompact,too).AddingthatsnippetwiththeImportErrorisn'tquitethebestideaduetoitmisleadingreadersthatOrderedDicthasnouse. – DimitrisFasarakisHilliard Dec10,2016at13:33 Inaresponsetothisanswer,andstructureddicts,Ipostedanewanswer.Feedbackwelcome! – BramVanroy Mar2,2018at16:49 Addacomment  |  83 Itcanoftenbeveryhandytousenamedtuple.Forexample,youhaveadictionaryof'name'askeysand'score'asvaluesandyouwanttosorton'score': importcollections Player=collections.namedtuple('Player','scorename') d={'John':5,'Alex':10,'Richard':7} sortingwithlowestscorefirst: worst=sorted(Player(v,k)for(k,v)ind.items()) sortingwithhighestscorefirst: best=sorted([Player(v,k)for(k,v)ind.items()],reverse=True) Nowyoucangetthenameandscoreof,let'ssaythesecond-bestplayer(index=1)veryPythonicallylikethis: player=best[1] player.name 'Richard' player.score 7 Share Improvethisanswer Follow editedApr24,2017at2:11 vallentin 21.6k66goldbadges5454silverbadges7474bronzebadges answeredAug30,2011at0:30 RemiRemi 19.7k88goldbadges5555silverbadges4141bronzebadges 2 HowcouldIconvertitbacktoadictionary? – rowana Feb7,2017at20:31 as_list=[Player(v,k)for(k,v)ind.items()]as_dict=dict((p.name,p.score)forpinas_list) – Remi Feb23,2017at12:31 Addacomment  |  52 Ihadthesameproblem,andIsolveditlikethis: WantedOutput=sorted(MyDict,key=lambdax:MyDict[x]) (Peoplewhoanswer"Itisnotpossibletosortadict"didnotreadthequestion!Infact,"Icansortonthekeys,buthowcanIsortbasedonthevalues?"clearlymeansthathewantsalistofthekeyssortedaccordingtothevalueoftheirvalues.) Pleasenoticethattheorderisnotwelldefined(keyswiththesamevaluewillbeinanarbitraryorderintheoutputlist). Share Improvethisanswer Follow editedNov28,2017at13:44 PeterMortensen 30.2k2121goldbadges100100silverbadges124124bronzebadges answeredNov18,2010at14:19 jimifikijimifiki 5,18211goldbadge3232silverbadges5656bronzebadges 2 Notethatyou'rebothiteratingthedictionaryandfetchingvaluesbytheirkey,soperformancewisethisisnotanoptimalsolution. – RonKlein Sep21,2016at8:00 1 @Dejell:asthecontributorsays,heinterpretsthequestionas"canIgetthelistofkeyssortedaccordingtothevalues".Wedon'tneedthevaluesintheresult,wehavetheminthedictionary. – Max Jan12,2019at3:19 Addacomment  |  50 IfvaluesarenumericyoumayalsouseCounterfromcollections. fromcollectionsimportCounter x={'hello':1,'python':5,'world':3} c=Counter(x) print(c.most_common()) >>[('python',5),('world',3),('hello',1)] Share Improvethisanswer Follow editedMay17,2019at13:48 Georgy 10.4k77goldbadges5959silverbadges6767bronzebadges answeredJun27,2012at15:43 IvanSasIvanSas 98311goldbadge99silverbadges1414bronzebadges 2 whataboutifyoudictionaryis>>>x={'hello':1,'python':5,'world':300} – JamesSapam Dec28,2013at13:17 @yopyCounter({'hello':1,'python':5,'world':300}).most_common()gives[('world',300),('python',5),('hello',1)].Thisactuallyworksforanysortablevaluetype(althoughmanyotherCounteroperationsdorequirevaluestobecomparabletoints). – lvc Dec28,2013at13:58 Addacomment  |  41 InPython2.7,simplydo: fromcollectionsimportOrderedDict #regularunsorteddictionary d={'banana':3,'apple':4,'pear':1,'orange':2} #dictionarysortedbykey OrderedDict(sorted(d.items(),key=lambdat:t[0])) OrderedDict([('apple',4),('banana',3),('orange',2),('pear',1)]) #dictionarysortedbyvalue OrderedDict(sorted(d.items(),key=lambdat:t[1])) OrderedDict([('pear',1),('orange',2),('banana',3),('apple',4)]) copy-pastefrom:http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes Enjoy;-) Share Improvethisanswer Follow answeredAug22,2013at8:38 sweetdreamsweetdream 1,1611111silverbadges1313bronzebadges Addacomment  |  31 Thisisthecode: importoperator origin_list=[ {"name":"foo","rank":0,"rofl":20000}, {"name":"Silly","rank":15,"rofl":1000}, {"name":"Baa","rank":300,"rofl":20}, {"name":"Zoo","rank":10,"rofl":200}, {"name":"Penguin","rank":-1,"rofl":10000} ] print">>Original>>" forfooinorigin_list: printfoo print"\n>>Roflsort>>" forfooinsorted(origin_list,key=operator.itemgetter("rofl")): printfoo print"\n>>Ranksort>>" forfooinsorted(origin_list,key=operator.itemgetter("rank")): printfoo Herearetheresults: Original {'name':'foo','rank':0,'rofl':20000} {'name':'Silly','rank':15,'rofl':1000} {'name':'Baa','rank':300,'rofl':20} {'name':'Zoo','rank':10,'rofl':200} {'name':'Penguin','rank':-1,'rofl':10000} Rofl {'name':'Baa','rank':300,'rofl':20} {'name':'Zoo','rank':10,'rofl':200} {'name':'Silly','rank':15,'rofl':1000} {'name':'Penguin','rank':-1,'rofl':10000} {'name':'foo','rank':0,'rofl':20000} Rank {'name':'Penguin','rank':-1,'rofl':10000} {'name':'foo','rank':0,'rofl':20000} {'name':'Zoo','rank':10,'rofl':200} {'name':'Silly','rank':15,'rofl':1000} {'name':'Baa','rank':300,'rofl':20} Share Improvethisanswer Follow editedMar2,2016at7:42 icedwater 4,54233goldbadges3333silverbadges4747bronzebadges answeredMar8,2011at2:06 PedroMorganPedroMorgan 8981212silverbadges1515bronzebadges Addacomment  |  31 Trythefollowingapproach.Letusdefineadictionarycalledmydictwiththefollowingdata: mydict={'carl':40, 'alan':2, 'bob':1, 'danny':3} Ifonewantedtosortthedictionarybykeys,onecoulddosomethinglike: forkeyinsorted(mydict.iterkeys()): print"%s:%s"%(key,mydict[key]) Thisshouldreturnthefollowingoutput: alan:2 bob:1 carl:40 danny:3 Ontheotherhand,ifonewantedtosortadictionarybyvalue(asisaskedinthequestion),onecoulddothefollowing: forkey,valueinsorted(mydict.iteritems(),key=lambda(k,v):(v,k)): print"%s:%s"%(key,value) Theresultofthiscommand(sortingthedictionarybyvalue)shouldreturnthefollowing: bob:1 alan:2 danny:3 carl:40 Share Improvethisanswer Follow editedMay23,2018at23:11 PeterMortensen 30.2k2121goldbadges100100silverbadges124124bronzebadges answeredApr7,2014at4:46 NathanielPayneNathanielPayne 2,70911goldbadge2626silverbadges3232bronzebadges 2 Awesome!forkey,valueinsorted(mydict.iteritems(),key=lambda(k,v):v["score"]):allowsyoutosortbyasubkey – Andomar Jul7,2017at19:08 thisdoesn'tworkinlaterversionsofpythonthatdontsupporttupleunpackingandwheredictsnolongerhaveiteritems() – lb_so Jun5,2021at10:30 Addacomment  |  30 StartingfromPython3.6,dictobjectsarenoworderedbyinsertionorder.It'sofficiallyinthespecsofPython3.7. >>>words={"python":2,"blah":4,"alice":3} >>>dict(sorted(words.items(),key=lambdax:x[1])) {'python':2,'alice':3,'blah':4} Beforethat,youhadtouseOrderedDict. Python3.7documentationsays: Changedinversion3.7:Dictionaryorderisguaranteedtobeinsertion order.ThisbehaviorwasimplementationdetailofCPythonfrom3.6. Share Improvethisanswer Follow editedOct24,2018at14:19 answeredSep15,2018at13:37 MaximeChéramyMaximeChéramy 16.6k77goldbadges5252silverbadges7474bronzebadges 1 worksgreat!dict(sorted(words.items(),key=lambdax:x[1],reverse=True))forDESC – vizyourdata Nov19,2018at20:10 Addacomment  |  27 Youcancreatean"invertedindex",also fromcollectionsimportdefaultdict inverse=defaultdict(list) fork,vinoriginalDict.items(): inverse[v].append(k) Nowyourinversehasthevalues;eachvaluehasalistofapplicablekeys. forkinsorted(inverse): printk,inverse[k] Share Improvethisanswer Follow answeredMar5,2009at1:52 S.LottS.Lott 375k7878goldbadges500500silverbadges769769bronzebadges Addacomment  |  25 Youcanusethecollections.Counter.Note,thiswillworkforbothnumericandnon-numericvalues. >>>x={1:2,3:4,4:3,2:1,0:0} >>>fromcollectionsimportCounter >>>#Tosortinreverseorder >>>Counter(x).most_common() [(3,4),(4,3),(1,2),(2,1),(0,0)] >>>#Tosortinascendingorder >>>Counter(x).most_common()[::-1] [(0,0),(2,1),(1,2),(4,3),(3,4)] >>>#Togetadictionarysortedbyvalues >>>fromcollectionsimportOrderedDict >>>OrderedDict(Counter(x).most_common()[::-1]) OrderedDict([(0,0),(2,1),(1,2),(4,3),(3,4)]) Share Improvethisanswer Follow editedApr3,2014at17:04 PeterMortensen 30.2k2121goldbadges100100silverbadges124124bronzebadges answeredMar9,2013at12:30 AbhijitAbhijit 59.5k1717goldbadges123123silverbadges196196bronzebadges 1 7 HowisthisdifferentfromIvanSas'sanswer? – PeterMortensen Apr3,2014at17:07 Addacomment  |  20 Youcanuseaskipdictwhichisadictionarythat'spermanentlysortedbyvalue. >>>data={1:2,3:4,4:3,2:1,0:0} >>>SkipDict(data) {0:0.0,2:1.0,1:2.0,4:3.0,3:4.0} Ifyouusekeys(),values()oritems()thenyou'lliterateinsortedorderbyvalue. It'simplementedusingtheskiplistdatastructure. Share Improvethisanswer Follow answeredSep25,2014at22:56 malthemalthe 9451010silverbadges2020bronzebadges 2 canwechangetheorderofsort,rightnow,itisasending,butIwantdecsending. – SulemanElahi Feb6,2020at12:15 afaikyouwouldhavetonegateyourvaluesinordertoreversetheordering – malthe Feb6,2020at13:14 Addacomment  |  19 Youcanalsousecustomfunctionthatcanbepassedtokey. defdict_val(x): returnx[1] x={1:2,3:4,4:3,2:1,0:0} sorted_x=sorted(x.items(),key=dict_val) Share Improvethisanswer Follow editedMay17,2019at14:55 Georgy 10.4k77goldbadges5959silverbadges6767bronzebadges answeredMay25,2017at18:13 VishwanathRawatVishwanathRawat 47766silverbadges1111bronzebadges 1 Thisistheonlyanswerthatworkedsofarinpython2.7 – rkochev Jan19,2021at12:44 Addacomment  |  18 Thecollectionssolutionmentionedinanotheranswerisabsolutelysuperb,becauseyouretainaconnectionbetweenthekeyandvaluewhichinthecaseofdictionariesisextremelyimportant. Idon'tagreewiththenumberonechoicepresentedinanotheranswer,becauseitthrowsawaythekeys. Iusedthesolutionmentionedabove(codeshownbelow)andretainedaccesstobothkeysandvaluesandinmycasetheorderingwasonthevalues,buttheimportancewastheorderingofthekeysafterorderingthevalues. fromcollectionsimportCounter x={'hello':1,'python':5,'world':3} c=Counter(x) print(c.most_common()) >>[('python',5),('world',3),('hello',1)] Share Improvethisanswer Follow editedOct7,2021at10:56 answeredMar3,2014at14:58 EamonnKennyEamonnKenny 1,6611616silverbadges1717bronzebadges 0 Addacomment  |  17 Ofcourse,remember,youneedtouseOrderedDictbecauseregularPythondictionariesdon'tkeeptheoriginalorder. fromcollectionsimportOrderedDict a=OrderedDict(sorted(originalDict.items(),key=lambdax:x[1])) IfyoudonothavePython2.7orhigher,thebestyoucandoisiterateoverthevaluesinageneratorfunction.(ThereisanOrderedDictfor2.4and2.6here,but a)Idon'tknowabouthowwellitworks and b)Youhavetodownloadandinstallitofcourse.Ifyoudonothaveadministrativeaccess,thenI'mafraidtheoption'sout.) defgen(originalDict): forx,yinsorted(zip(originalDict.keys(),originalDict.values()),key=lambdaz:z[1]): yield(x,y) #Yieldsasatuplewith(key,value).Youcaniteratewithconditionalclausestogetwhatyouwant. forbleh,mehingen(myDict): ifbleh=="foo": print(myDict[bleh]) Youcanalsoprintouteveryvalue forbleh,mehingen(myDict): print(bleh,meh) PleaseremembertoremovetheparenthesesafterprintifnotusingPython3.0orabove Share Improvethisanswer Follow editedMay17,2019at16:17 Georgy 10.4k77goldbadges5959silverbadges6767bronzebadges answeredJul31,2015at8:08 rassa45rassa45 3,40611goldbadge2828silverbadges4343bronzebadges 1 1 regularPythondictionariesdon'tkeeptheoriginalorder—asofPython3.7,theydo. – gerrit Dec19,2018at17:13 Addacomment  |  16 fromdjango.utils.datastructuresimportSortedDict defsortedDictByKey(self,data): """Sorteddictionaryorderbykey""" sortedDict=SortedDict() ifdata: ifisinstance(data,dict): sortedKey=sorted(data.keys()) forkinsortedKey: sortedDict[k]=data[k] returnsortedDict Share Improvethisanswer Follow answeredNov1,2010at12:16 ArgunArgun 41755silverbadges2020bronzebadges 1 2 questionwas:sortbyvalue,notbykeys...Ilikeseeingafunction.Youcanimportcollectionsandofcourseusesorted(data.values()) – Remi Aug30,2011at0:38 Addacomment  |  15 Hereisasolutionusingzipond.values()andd.keys().Afewlinesdownthislink(onDictionaryviewobjects)is: Thisallowsthecreationof(value,key)pairsusingzip():pairs=zip(d.values(),d.keys()). Sowecandothefollowing: d={'key1':874.7,'key2':5,'key3':8.1} d_sorted=sorted(zip(d.values(),d.keys())) printd_sorted #prints:[(5,'key2'),(8.1,'key3'),(874.7,'key1')] Share Improvethisanswer Follow answeredJun20,2015at1:44 ScottScott 5,66344goldbadges3434silverbadges5050bronzebadges 0 Addacomment  |  14 AspointedoutbyDilettant,Python3.6willnowkeeptheorder!IthoughtI'dshareafunctionIwrotethateasesthesortingofaniterable(tuple,list,dict).Inthelattercase,youcansorteitheronkeysorvalues,anditcantakenumericcomparisonintoaccount.Onlyfor>=3.6! Whenyoutryusingsortedonaniterablethatholdse.g.stringsaswellasints,sorted()willfail.Ofcourseyoucanforcestringcomparisonwithstr().However,insomecasesyouwanttodoactualnumericcomparisonwhere12issmallerthan20(whichisnotthecaseinstringcomparison).SoIcameupwiththefollowing.Whenyouwantexplicitnumericcomparisonyoucanusetheflagnum_as_numwhichwilltrytodoexplicitnumericsortingbytryingtoconvertallvaluestofloats.Ifthatsucceeds,itwilldonumericsorting,otherwiseit'llresorttostringcomparison. Commentsforimprovementwelcome. defsort_iterable(iterable,sort_on=None,reverse=False,num_as_num=False): def_sort(i): #sortby0=keys,1values,Noneforlistsandtuples try: ifnum_as_num: ifiisNone: _sorted=sorted(iterable,key=lambdav:float(v),reverse=reverse) else: _sorted=dict(sorted(iterable.items(),key=lambdav:float(v[i]),reverse=reverse)) else: raiseTypeError except(TypeError,ValueError): ifiisNone: _sorted=sorted(iterable,key=lambdav:str(v),reverse=reverse) else: _sorted=dict(sorted(iterable.items(),key=lambdav:str(v[i]),reverse=reverse)) return_sorted ifisinstance(iterable,list): sorted_list=_sort(None) returnsorted_list elifisinstance(iterable,tuple): sorted_list=tuple(_sort(None)) returnsorted_list elifisinstance(iterable,dict): ifsort_on=='keys': sorted_dict=_sort(0) returnsorted_dict elifsort_on=='values': sorted_dict=_sort(1) returnsorted_dict elifsort_onisnotNone: raiseValueError(f"Unexpectedvalue{sort_on}forsort_on.Whensortingadict,usekeyorvalues") else: raiseTypeError(f"Unexpectedtype{type(iterable)}foriterable.Expectedalist,tuple,ordict") Share Improvethisanswer Follow editedFeb19,2021at9:00 answeredMar2,2018at16:48 BramVanroyBramVanroy 25.3k2121goldbadges122122silverbadges216216bronzebadges Addacomment  |  11 JustlearnedrelevantskillfromPythonforEverybody. Youmayuseatemporarylisttohelpyoutosortthedictionary: #Assumedictionarytobe: d={'apple':500.1,'banana':1500.2,'orange':1.0,'pineapple':789.0} #createatemporarylist tmp=[] #iteratethroughthedictionaryandappendeachtupleintothetemporarylist forkey,valueind.items(): tmptuple=(value,key) tmp.append(tmptuple) #sortthelistinascendingorder tmp=sorted(tmp) print(tmp) Ifyouwanttosortthelistindescendingorder,simplychangetheoriginalsortinglineto: tmp=sorted(tmp,reverse=True) Usinglistcomprehension,theonelinerwouldbe: #Assumingthedictionarylookslike d={'apple':500.1,'banana':1500.2,'orange':1.0,'pineapple':789.0} #Onelinerforsortinginascendingorder print(sorted([(v,k)fork,vind.items()])) #Onelinerforsortingindescendingorder print(sorted([(v,k)fork,vind.items()],reverse=True)) SampleOutput: #Asendingorder [(1.0,'orange'),(500.1,'apple'),(789.0,'pineapple'),(1500.2,'banana')] #Descendingorder [(1500.2,'banana'),(789.0,'pineapple'),(500.1,'apple'),(1.0,'orange')] Share Improvethisanswer Follow editedMay27,2018at17:59 answeredMay27,2018at17:45 mcgagmcgag 19511silverbadge1313bronzebadges 1 Ifyouwanttoprintitintheinitialformatyoushoulddo:print([(k,v)forv,kinsorted([(v,k)fork,vind.items()])]).Theoutputis:[('orange',1.0),('apple',500.1),('pineapple',789.0),('banana',1500.2)].With[(k,v)forv,kinsorted([(v,k)fork,vind.items()],reverse=True)]theoutputis:[('banana',1500.2),('pineapple',789.0),('apple',500.1),('orange',1.0)] – HermesMorales May4,2020at20:14 Addacomment  |  10 UseValueSortedDictfromdicts: fromdicts.sorteddictimportValueSortedDict d={1:2,3:4,4:3,2:1,0:0} sorted_dict=ValueSortedDict(d) printsorted_dict.items() [(0,0),(2,1),(1,2),(4,3),(3,4)] Share Improvethisanswer Follow answeredOct19,2011at6:25 pontyponty 59477silverbadges88bronzebadges Addacomment  |  10 Iteratethroughadictandsortitbyitsvaluesindescendingorder: $python--version Python3.2.2 $catsort_dict_by_val_desc.py dictionary=dict(siis=1,sana=2,joka=3,tuli=4,aina=5) forwordinsorted(dictionary,key=dictionary.get,reverse=True): print(word,dictionary[word]) $pythonsort_dict_by_val_desc.py aina5 tuli4 joka3 sana2 siis1 Share Improvethisanswer Follow answeredOct30,2011at19:42 juhohjuhoh 10911silverbadge22bronzebadges Addacomment  |  9 Ifyourvaluesareintegers,andyouusePython2.7ornewer,youcanusecollections.Counterinsteadofdict.Themost_commonmethodwillgiveyouallitems,sortedbythevalue. Share Improvethisanswer Follow editedJan24,2012at19:50 answeredJan24,2012at19:28 PetrViktorinPetrViktorin 63.2k88goldbadges7979silverbadges7878bronzebadges Addacomment  |  8 Thisworksin3.1.x: importoperator slovar_sorted=sorted(slovar.items(),key=operator.itemgetter(1),reverse=True) print(slovar_sorted) Share Improvethisanswer Follow editedNov6,2012at19:27 NathanielFord 19.1k2020goldbadges8383silverbadges9494bronzebadges answeredNov16,2011at7:32 iFailiFail 8911silverbadge11bronzebadge Addacomment  |  8 Forthesakeofcompleteness,Iampostingasolutionusingheapq.Note,thismethodwillworkforbothnumericandnon-numericvalues >>>x={1:2,3:4,4:3,2:1,0:0} >>>x_items=x.items() >>>heapq.heapify(x_items) >>>#Tosortinreverseorder >>>heapq.nlargest(len(x_items),x_items,operator.itemgetter(1)) [(3,4),(4,3),(1,2),(2,1),(0,0)] >>>#Tosortinascendingorder >>>heapq.nsmallest(len(x_items),x_items,operator.itemgetter(1)) [(0,0),(2,1),(1,2),(4,3),(3,4)] Share Improvethisanswer Follow answeredMar23,2013at14:19 AbhijitAbhijit 59.5k1717goldbadges123123silverbadges196196bronzebadges Addacomment  |  1 2 Next Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonsortingdictionaryoraskyourownquestion. TheOverflowBlog Measurableandmeaningfulskilllevelsfordevelopers SanFrancisco?MorelikeSanFrancis-go(Ep.468) FeaturedonMeta AnnouncingtheStacksEditorBetarelease! The[shopping]and[shop]tagsarebeingburninated Linked 148 Sortingdictionarykeysinpython 94 sortdictbyvaluepython 52 sortvaluesandreturnlistofkeysfromdictpython 21 Sortdictbyhighestvalue? 38 Howtosortadictionarybykey? 27 SortPythondictbydatetimevalue 14 Howtogetthe3itemswiththehighestvaluefromdictionary? 16 Sortdictbyvalueandreturndict,notlistoftuples 8 sortlistbyfrequency-valueinpython 7 Howtousethedictionaryfunction? Seemorelinkedquestions Related 908 Howdoyousortadictionarybyvalue? 6385 HowdoImergetwodictionariesinasingleexpression? 2528 HowdoIsortalistofdictionariesbyavalueofthedictionary? 3079 Howtoiterateoveradictionary? 1260 Gettingkeywithmaximumvalueindictionary? 1088 Howtosortalistofobjectsbasedonanattributeoftheobjects? 3343 HowcanIaddnewkeystoadictionary? 3743 Sortarrayofobjectsbystringpropertyvalue 1523 HowtoSortaListbyapropertyintheobject HotNetworkQuestions WhydidthefolksatMarvelStudiosremovethecharacterDeathfromtheInfinitySaga? Meaningof'glassthat'swithcanarylined'? WhydoesrsyncgivedifferentoutputbetweenrsyncingtoaUSBflashdriveversusaharddisk? HaveanymilitarypersonnelservingademocraticstatebeenprosecutedaccordingtothefourthNurembergprinciple(superiororder)? Isitnecessarytoprovidecontactinformationfortensofco-authorswhensubmittingapaperfromalargecollaboration? Supportforsurrogacyfrompro-choicegroups Alternativewordorphraseto"result"incomputerjargon Whyaremagneticfieldlinesimaginary? Whoarethesevillainsnamed'Control'inCaptainAmericaandtheAvengers? WhatistheUbuntuServerGUIwifisetuppackage? Howwoulduncurvedseashoresform? Perl:speedofs/// IsitpossibletoturnNormalUbuntuLiveUSBtopersistentUSB(withoutanyotherdevicesorUSBsticks)? Asa(non)residentalienintheUS,whatdocuments(ifany)doesoneneedtocarryatalltimes? DoIneedanotarizedminorconsentformfrombothparentstotravel? Howgamebreakingisthismagicitemthatcanreducecastingtimes? Ifasampleisnormallydistributed,isitspopulationalwaysnormallydistributed? CanaUScitizenwho'sneverlivedinUSvoteinUS? HowcanItellwhenFFMPEGisdonewritingafile? AirbrakesonF-35behindthecockpit Submittingrevisedmanuscriptlongbeforeduedate Iscodathesamethingasacadence? Whyisthereawhitepanelinastronaut’sfabricheadcovertheywearinsidethehardhelmet? LinkedListimplementationinc++withallfunctions morehotquestions lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?