Python - Sort Dictionary key and values List - GeeksforGeeks

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

In this, we initially sort all the values of keys, and then perform the keys sorting after that, in brute manner. Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonReadJSONfileusingPythonHowtogetcolumnnamesinPandasdataframeReadafilelinebylineinPythonIterateoveralistinPythonPythonprogramtoconvertalisttostringPythonDictionaryReadingandWritingtotextfilesinPythonPythonString|replace()Enumerate()inPythonDifferentwaystocreatePandasDataframesum()functioninPythonPrintlistsinPython(5DifferentWays)isupper(),islower(),lower(),upper()inPythonandtheirapplicationsConvertintegertostringinPython*argsand**kwargsinPythonPythonListsPython|GetalistasinputfromuserPythonString|split()Python|ProgramtoconvertStringtoaListCreateaPandasDataFramefromListsGraphPlottinginPython|Set1floor()andceil()functionPythonTakingmultipleinputsfromuserinPythonGETandPOSTrequestsusingPythonFindaverageofalistinpythonPythonStringfind()methodStackinPythonAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonReadJSONfileusingPythonHowtogetcolumnnamesinPandasdataframeReadafilelinebylineinPythonIterateoveralistinPythonPythonprogramtoconvertalisttostringPythonDictionaryReadingandWritingtotextfilesinPythonPythonString|replace()Enumerate()inPythonDifferentwaystocreatePandasDataframesum()functioninPythonPrintlistsinPython(5DifferentWays)isupper(),islower(),lower(),upper()inPythonandtheirapplicationsConvertintegertostringinPython*argsand**kwargsinPythonPythonListsPython|GetalistasinputfromuserPythonString|split()Python|ProgramtoconvertStringtoaListCreateaPandasDataFramefromListsGraphPlottinginPython|Set1floor()andceil()functionPythonTakingmultipleinputsfromuserinPythonGETandPOSTrequestsusingPythonFindaverageofalistinpythonPythonStringfind()methodStackinPythonPython–SortDictionarykeyandvaluesListViewDiscussion ImproveArticle SaveArticle LikeArticle LastUpdated: 02Jun,2020Sometimes,whileworkingwithPythondictionaries,wecanhaveaprobleminwhichweneedtoperformthesortingofit,wrtkeys,butalsocanhaveavariationinwhichweneedtoperformasortonitsvalueslistaswell.Let’sdiscusscertainwayinwhichthistaskcanbeperformed.Input:test_dict={‘c’:[3],‘b’:[12,10],‘a’:[19,4]}Output:{‘a’:[4,19],‘b’:[10,12],‘c’:[3]}Input:test_dict={‘c’:[10,34,3]}Output:{‘c’:[3,10,34]}Method#1:Usingsorted()+loopThecombinationofabovefunctionscanbeusedtosolvethisproblem.Inthis,weinitiallysortallthevaluesofkeys,andthenperformthekeyssortingafterthat,inbrutemanner.#Python3codetodemonstrateworkingof #SortDictionarykeyandvaluesList#Usingloop+dictionarycomprehension  #initializingdictionarytest_dict={'gfg':[7,6,3],              'is':[2,10,3],              'best':[19,4]}  #printingoriginaldictionaryprint("Theoriginaldictionaryis:"+str(test_dict))  #SortDictionarykeyandvaluesList#Usingloop+dictionarycomprehensionres=dict()forkeyinsorted(test_dict):    res[key]=sorted(test_dict[key])  #printingresult print("Thesorteddictionary:"+str(res)) Output:Theoriginaldictionaryis:{‘gfg’:[7,6,3],‘is’:[2,10,3],‘best’:[19,4]}Thesorteddictionary:{‘best’:[4,19],‘gfg’:[3,6,7],‘is’:[2,3,10]} Method#2:Usingdictionarycomprehension+sorted()Thecombinationofabovefunctionscanbeusedtosolvethisproblem.Inthis,weperformthetaskofdualsortinginsidedictionarycomprehensionconstruct.#Python3codetodemonstrateworkingof #SortDictionarykeyandvaluesList#Usingdictionarycomprehension+sorted()  #initializingdictionarytest_dict={'gfg':[7,6,3],              'is':[2,10,3],              'best':[19,4]}  #printingoriginaldictionaryprint("Theoriginaldictionaryis:"+str(test_dict))  #SortDictionarykeyandvaluesList#Usingdictionarycomprehension+sorted()res={key:sorted(test_dict[key])forkeyinsorted(test_dict)}  #printingresult print("Thesorteddictionary:"+str(res)) Output:Theoriginaldictionaryis:{‘gfg’:[7,6,3],‘is’:[2,10,3],‘best’:[19,4]}Thesorteddictionary:{‘best’:[4,19],‘gfg’:[3,6,7],‘is’:[2,3,10]}MyPersonalNotes arrow_drop_upSave LikePreviousJupyternotebookVSPythonIDLENext FormatspecifiersindifferentProgrammingLanguagesRecommendedArticlesPage:24,Aug2031,Jul2021,Feb1912,Apr2025,Sep2005,Oct2024,Aug2016,Apr2002,Apr2001,Jul2027,Aug2030,Jul2012,Feb1926,Jul1912,Apr2006,May2022,Aug2021,Apr2001,Jul2006,May2016,May1930,Apr2027,Jul2009,Nov20ArticleContributedBy:manjeet_04@manjeet_04VotefordifficultyEasy Normal Medium Hard ExpertArticleTags:Pythondictionary-programsPythonPythonProgramsReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?