python - Sorting a dictionary with lists as values, according to ...
文章推薦指數: 80 %
Here is one way to do this: >>> sorted(myDict.items(), key=lambda e: e[1][2]) [('item2', [8, 2, 3]), ('item1', [7, 1, 9]), ('item3', [9, 3, ... 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 Sortingadictionarywithlistsasvalues,accordingtoanelementfromthelist AskQuestion Asked 13yearsago Modified 1year,2monthsago Viewed 45ktimes 52 22 Iwanttosortadictionaryoflists,bythirditemineachlist.It'seasyenoughsortingadictionarybyvaluewhenthevalueisjustasinglenumberorstring,butthislistthinghasmebaffled. Example: myDict={'item1':[7,1,9],'item2':[8,2,3],'item3':[9,3,11]} Iwanttobeabletoiteratethroughthedictionaryinorderofthethirdvalueineachlist,inthiscaseitem2,item1thenitem3. pythonlistsortingdictionary Share Improvethisquestion Follow editedJan22,2021at13:00 Tomerikoo 16.4k1515goldbadges3737silverbadges5353bronzebadges askedAug1,2009at19:07 jayjay 64511goldbadge66silverbadges66bronzebadges 0 Addacomment | 4Answers 4 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 66 Hereisonewaytodothis: >>>sorted(myDict.items(),key=lambdae:e[1][2]) [('item2',[8,2,3]),('item1',[7,1,9]),('item3',[9,3,11])] Thekeyargumentofthesortedfunctionletsyouderiveasortingkeyforeachelementofthelist. Toiterateoverthekeys/valuesinthislist,youcanusesomethinglike: >>>forkey,valueinsorted(myDict.items(),key=lambdae:e[1][2]): ...printkey,value ... item2[8,2,3] item1[7,1,9] item3[9,3,11] Share Improvethisanswer Follow answeredAug1,2009at19:15 AymanHouriehAymanHourieh 124k2222goldbadges140140silverbadges115115bronzebadges 6 1 AssoonasIaskedthequestionIhadanepiphanyandbasicallycameupwiththesamethingexceptforthelambda(haven'tlearnedaboutthemyet).Justwrotemyowncmpfunctionthattakesintupplesfromdict.items()andreturnstheresult.Samething,justadifferentwaytowriteit.Thanksmuchforthequickreply! – jay Aug1,2009at19:21 Greatsolution.Ilovethesimplicityofsorted(). – EvanFosmark Aug1,2009at19:24 10 Ithinkitisalittleclearerthisway:sorted(myDict.items(),key=lambda(k,v):v[2]) – RobertoBonvallet Aug2,2009at1:08 @jay,key=ismuchbetterthancmp=performance-wise--AND,SOetiquettesuggestsyoushouldACCEPTthisanswerratherthanjustexpressingthanksforitverbally!!! – AlexMartelli Aug2,2009at1:21 "exceptforthelambda(haven'tlearnedaboutthemyet"Goodpoint.Avoidlambdaswherepossible.Thiscanbedonewithanordinaryfunctiondef,whichisusuallymuchmoreclearthanalambda. – S.Lott Aug2,2009at1:43 | Show1morecomment 4 Youstatedtwoquitedifferentwants: "WhatIwanttodoissortadictionaryoflists..." "Iwanttobeabletoiteratethroughthedictionaryinorderof..." Thefirstofthoseisbydefinitionimpossible--tosortsomethingimpliesarearrangementinsomeorder.Pythondictionariesareinherentlyunordered.Thesecondwouldbevaguelypossiblebutextremelyunlikelytobeimplemented. Whatyoucandois Takeacopyofthedictionarycontents(whichwillbequite unordered) Sortthat Iterateoverthesortedresults--andyoualreadyhavetwo solutionsforthat.Bytheway,thesolutionthatuses"key"instead of"cmp"isbetter;seesorted "thethirditeminthelist"smellslike"thethirditeminatuple"tome,and"e[1][2]"justsmells:-)...youmayliketoinvestigateusingnamedtuplesinsteadoflists;seenamedtuplefactory Ifyouaregoingtobedoingextract/sort/processoftenonlargedatasets,youmightliketoconsidersomethinglikethis,usingthePython-suppliedsqlite3module: createtableex_dict(ktextprimarykey,v0int,v1int,v2int); insertintoex_dictvalues('item1',7,1,9); --etcetc select*fromex_dictorderbyv2; Share Improvethisanswer Follow editedJul10,2014at17:58 undefinedvariable 66677silverbadges2020bronzebadges answeredAug2,2009at0:04 JohnMachinJohnMachin 79k1111goldbadges136136silverbadges182182bronzebadges 1 WorthnotingthatsincePython3.7,dictsactuallydomaintaininsertionorderofelements – Tomerikoo Jan22,2021at12:55 Addacomment | 3 AsJohnMachlinsaidyoucan'tactuallysortaPythondictionary. However,youcancreateanindexofthekeyswhichcanbesortedinanyorderyoulike. ThepreferredPythonpattern(idiom)forsortingbyanyalternativecriteriumiscalled"decorate-sort-undecorate"(DSU).Inthisidiomyoucreateatemporarylistwhichcontainstuplesofyourkey(s)followedbyyouroriginaldataelements,thencallthenormal.sort()methodonthatlist(or,inmorerecentversionsofPythonsimplywrapyourdecorationinacalledtothesorted()built-infunction).Thenyouremovethe"decorations." Thereasonthisisgenerallypreferredoverpassingcomparisonfunctiontothe.sort()methodisthatPython'sbuilt-indefaultsortingcode(compiledCinthenormalCPython)isveryfastandefficientinthedefaultcase,butmuch,muchslowerwhenithastocallPythonobjectcodemany,manytimesinthenon-defaultcase.Soit'susuallyfarbettertoiterateoverthedatacreatingdatastructureswhichcanbepassedtothedefaultsortroutines. Inthiscaseyoushouldbeabletousesomethinglike: [y[1]foryinsorted([(myDict[x][2],x)forxinmyDict.keys()])] ...that'salistcomprehensiondoingtheundecoratefromthesortedlistoftupleswhichisbeingreturnedbytheinnerlistcomprehension.Theinnercomprehensioniscreatingasetoftuples,yourdesiredsortingkey(the3rdelementofthelist)andthedictionary'skeycorrespondingtothesortingkey.myDict.keys()is,ofcourse,amethodofPythondictionarieswhichreturnsalistofallvalidkeysinwhateverordertheunderlyingimplementationchooses---presumablyasimpleiterationoverthehashes. Amoreverbosewayofdoingthismightbeeasiertoread: temp=list() fork,vinmyDict.items(): temp.append((v[2],)) temp.sort() results=list() foriintemp: results.append(i[1]) Usuallyyoushouldbuiltupsuchcodeiteratively,intheinterpreterusingsmalldatasamples.Buildthe"decorate"expressionorfunction.Thenwrapthatinacalltosorted().Thenbuildtheundecorateexpression(whichisusuallyassimpleaswhatI'veshownhere). Share Improvethisanswer Follow answeredAug2,2009at10:01 JimDennisJimDennis 16.5k1111goldbadges6161silverbadges113113bronzebadges 1 (1)Youcomparedecorate-sort-undecoratewithusingthecmparg;introductionofthekeyargchoppedoffaverylargesliceofDSU'sterritory.(2)YoursolutionleavestheOPwithalistofthedictkeys...togetwhathewants,he'llhavetodoyetanotherloopofthedictitems(3)yourverbosewayhasatypo:s/v[2],/v[2],k/ – JohnMachin Aug2,2009at13:13 Addacomment | 0 Nowyoucandothis;returnsadictionaryitself.Booleanattheendistodetermineiftheorderisascendingordescending. sorted_dict=dict(sorted(myDict.items(),key=lambdaitem:item[1][2],reverse=True)) Share Improvethisanswer Follow answeredMay22,2021at20:27 fayizdasmafayizdasma 2155bronzebadges Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonlistsortingdictionaryoraskyourownquestion. TheOverflowBlog Measurableandmeaningfulskilllevelsfordevelopers SanFrancisco?MorelikeSanFrancis-go(Ep.468) FeaturedonMeta AnnouncingtheStacksEditorBetarelease! The[shopping]and[shop]tagsarebeingburninated Linked 1 Howtosortdictionarykeysbytheirappearanceinafile 0 HowtoorderadictionaryoflistsinPython -1 sortingdictionarywithlistvalue(python) -2 Howtosortthegivenpythondictionarywithalistasvalues,basedononeoftheelementsinlist? 18 CustomSortingPythonDictionary 6 SortingadictionaryofDictionaries-Python -1 HowdoIsortadictionarybyapartofthedictionaryvalues? -1 Howtoorderadictionarybyitsvalue,whichisanarrayof3values? 1 Howtosortadictionarybyvalueswhichcontainlistsinpython Related 2528 HowdoIsortalistofdictionariesbyavalueofthedictionary? 2040 Howtoremoveanelementfromalistbyindex 2603 HowdoIgetthelastelementofalist? 842 Howtosortalist/tupleoflists/tuplesbytheelementatagivenindex? 977 HowdoIremovethefirstitemfromalist? 1980 Deleteanelementfromadictionary 544 Sortinglistbasedonvaluesfromanotherlist 1531 HowcanIinstallpackagesusingpipaccordingtotherequirements.txtfilefromalocaldirectory? HotNetworkQuestions DidtheAlgol68standardallowaproceduretobecalledbeforeitsdeclaration? Perl:speedofs/// HowcanIredesignahigh-frequency,high-voltagepowersupplycausingEMIaroundthehome? Ifaspecieskeepsgrowingthroughouttheir200-300yearlife,what"growthcurve"wouldbemostreasonable/realistic? Wouldaspeareveroutperformabowwhenwieldedbyaninsanelypowerfulperson? Whywon'tthiselectromagnethomeexperimentwork? Whatis"RosencrantzandGuildenstern"in_TheMarvelousMrs.Maisel_season3episode5? Whatismeantbytheterm"beeline"inanaddress(latitude/longitude)? Submittingrevisedmanuscriptlongbeforeduedate ConfusionregardingHeisenbergUncertaintyPrinciple What’stheofficialin-universeclassificationofThorandotherAsgardiansintheMCU? DoesaVialofAcid,Oil,AlchemistFire,orotherimprovisedweaponadventuringgearstillrequireanObjectInteractionto'draw'first? Isthereanameforthisfallacywhensomeonesayssomethingisgoodbyonlypointingoutthegoodthings? Gravitationalforceactingonamasslessbody? What'sareasonableenvironmentaldisasterthatcouldbecausedbyaprobefromEarthenteringEuropa'socean? DidPharaohnotrecogniseMosesafterfortyyears? Howtoavoidstalemateintheposition? DoesthetitleofamasterprogrammakesadifferenceforalaterPhD? Iscodathesamethingasacadence? Asa(non)residentalienintheUS,whatdocuments(ifany)doesoneneedtocarryatalltimes? Whyisa220ΩresistorforthisLEDsuggestedifOhm'slawseemstosaymuchlessisrequired? WhatwasthepurposeofthosespecialuseraccountsinUnix? HowtoextendusefullifeofIRLEDandphotodiodepair FeedbackcapacitorvsMillercapacitorindiscreteopampcircuits morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1Python: Sort a Dictionary by Values - datagy
Sort a Python Dictionary by Values Using dict.items and Sorted ... The Python sorted() function a...
- 2How to Sort a Dictionary by Value in Python | Career Karma
- 3[python] Sort dictionary into list based on another dict · GitHub
[python] Sort dictionary into list based on another dict ... dict_key = {'a': 1, 'b': 3, 'c': 2} ...
- 4Python 3 - List sort() Method - Tutorialspoint
- 5Ways to sort list of dictionaries by values in Python
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always be...