Python에서 사전 순서 유지
Python의 사전은 본질적으로 순서가 없으므로 키를 정렬하기가 어렵습니다. 이 문서에서는 키를 기준으로 사전을 정렬하는 방법을 살펴봅니다.
표준 사전
표준 Python 사전은 (키, 값) 쌍에 대해 특정 순서를 유지하지 않습니다. 파리를 정렬하면 사전의 예측할 수 없는 순서가 변경됩니다.
OrderedDict: 솔루션
dict의 하위 클래스인 OrderedDict 클래스가 이 문제를 해결합니다. 요소의 삽입 순서를 기억하여 정렬 후에도 키가 순서대로 유지되도록 합니다.
import collections # Sample dictionary d = {2: 3, 1: 89, 4: 5, 3: 0} # Create an OrderedDict with sorted keys od = collections.OrderedDict(sorted(d.items())) # Print the sorted OrderedDict print(od)
출력:
OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
값 액세스
정렬된 키에도 불구하고 OrderedDict는 값에 대해 예상되는 동작을 유지합니다. access.
print(od[1]) # Prints 89 print(od[3]) # Prints 0
반복
OrderedDict를 통한 반복은 정렬된 키 순서를 유지합니다.
for k, v in od.items(): print(k, v)
출력:
1 89 2 3 3 0 4 5
파이썬 3
Python 3에서는 항목 반복을 위해 업데이트된 구문을 사용합니다.
for k, v in od.items(): print(k, v)
위 내용은 Python에서 정렬할 때 사전 키 순서를 어떻게 유지할 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

WebStorm Mac 버전
유용한 JavaScript 개발 도구