A dictionary has no order: if you add/remove/update elements in a dictionary, the order in which the keys are iterated can change.
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
bubblesortingindictionaryinpython
AskQuestion
Asked
3years,10monthsago
Modified
3years,10monthsago
Viewed
5ktimes
0
Iamtryingtodobubblesortindescendingorder
input={"m":1,"i":4,"s":4,"P":2}
output={"i":4,"s":4,"p":2,"m":1}
butatypeerroroccurs.HowcanIdothis?
Belowisthecode:
dict={"m":1,"i":4,"s":4,"P":2}
forkey,valueindict.items():
if(dict[key]>>my_list
[('m',1),('i',4),('s',4),('P',2)]
andthnenwecansortthelist(forexamplewithbubblesort)like:
formxinrange(len(my_list)-1,-1,-1):
swapped=False
foriinrange(mx):
ifmy_list[i][1]>>my_list
[('i',4),('s',4),('P',2),('m',1)]
Share
Improvethisanswer
Follow
answeredSep28,2018at8:16
WillemVanOnsemWillemVanOnsem
406k2929goldbadges378378silverbadges496496bronzebadges
0
Addacomment
|
1
doyoumeansomethinglikethis?
dict={"m":1,"i":4,"s":4,"P":2}
sorted_values=sorted(dict.values(),reverse=True)
printsorted_values
Butthisisn't"manual"bubblesort.Soifyouhavetotobubblesortthisbyyourownjustusethelistofvaluesvia
values=dict.values()
Andthensortthem;)
Astimgebalreadymentionedinacomment,I'msorrydidntseethecommentbeforeIwrotethispost.
Share
Improvethisanswer
Follow
editedSep28,2018at8:23
answeredSep28,2018at8:18
Loois95Loois95
851010bronzebadges
4
ButtheOPsaidtheoriginalquestionwastocountduplicateinadictionaryandcounttheduplicatevaluesindescendingorder....
– toti08
Sep28,2018at8:20
2
Thequestionspecifies:"Iamtryingtodobubblesortindescendingorder".But+1anyway..
– WillemVanOnsem
Sep28,2018at8:21
1
@WillemVanOnsemYeahthatswhyIwroteifhehastobubblesortthevalueshecanstartaftervalues=dict.values()andthenbubblesortthem...
– Loois95
Sep28,2018at8:21
MyintentionwastogivetheOPthehinttousethedict.values()function.
– Loois95
Sep28,2018at8:22
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?Browseotherquestionstaggedpythondictionarykey-valuebubble-sortoraskyourownquestion.
TheOverflowBlog
Measurableandmeaningfulskilllevelsfordevelopers
SanFrancisco?MorelikeSanFrancis-go(Ep.468)
FeaturedonMeta
AnnouncingtheStacksEditorBetarelease!
The[shopping]and[shop]tagsarebeingburninated
Related
6873
WhataremetaclassesinPython?
3079
Howtoiterateoveradictionary?
7398
DoesPythonhaveaternaryconditionaloperator?
3397
Convertbytestoastring
3416
HowdoIsortadictionarybyvalue?
3343
HowcanIaddnewkeystoadictionary?
2679
Checkifagivenkeyalreadyexistsinadictionary
2596
HowcanIremoveakeyfromaPythondictionary?
3511
HowtoiterateoverrowsinaDataFrameinPandas
2763
Whyis"1000000000000000inrange(1000000000000001)"sofastinPython3?
HotNetworkQuestions
Wasitaccurate(history-wise)forKoenigtoknowaboutrobots?
Page-turningnumberofagraph
HowcanIaccuratelydeterminethefontsizeinadocument?
RepeatHelloWorldaccordingtoanotherstring'slength
WhydoFrenchcustomssearchFlixBuses
HaveanymilitarypersonnelservingademocraticstatebeenprosecutedaccordingtothefourthNurembergprinciple(superiororder)?
AircraftoverParis
HowtoextendusefullifeofIRLEDandphotodiodepair
Ifasampleisnormallydistributed,isitspopulationalwaysnormallydistributed?
HowtoshufflecolumnsbyeveryanotherinR?
DoesthetitleofamasterprogrammakesadifferenceforalaterPhD?
newtagformyequation-environment
WhatdoestheAriane5rocketusetoturn?
Howgamebreakingisthismagicitemthatcanreducecastingtimes?
Onthebasisof"Veni,vidi,vici"is"Veni,bibi,oblidi"remotelycorrect?
DerivationoftheIndo-Europeanlemma*bʰréh₂tēr
Whoarethesevillainsnamed'Control'inCaptainAmericaandtheAvengers?
DoIneedanotarizedminorconsentformfrombothparentstotravel?
GenerateallPossibilitiesofWords
DidtheAlgol68standardallowaproceduretobecalledbeforeitsdeclaration?
Whyisthereawhitepanelinastronaut’sfabricheadcovertheywearinsidethehardhelmet?
WhydoesrsyncgivedifferentoutputbetweenrsyncingtoaUSBflashdriveversusaharddisk?
Newchainslipping
DoesaVialofAcid,Oil,AlchemistFire,orotherimprovisedweaponadventuringgearstillrequireanObjectInteractionto'draw'first?
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
lang-py
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings