한 컬렉션 유형에서 다른 컬렉션 유형으로 변환하는 것은 파이썬에서 매우 일반적입니다. 데이터 처리 요구 사항에 따라 사전에 있는 키 값 쌍을 목록의 튜플을 나타내는 쌍으로 변환해야 할 수도 있습니다. 이 기사에서는 이를 달성하기 위한 접근 방식을 살펴보겠습니다.
포함
이것은
예시
Adict = {30:'Mon',11:'Tue',19:'Fri'}
# Given dictionary
print("The given dictionary: ",Adict)
# Using in
Alist = [(key, val) for key, val in Adict.items()]
# Result
print("The list of tuples: ",Alist) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')] 지퍼 포함
zip 함수는 매개변수로 전달된 항목을 결합합니다. 따라서 사전의 키와 값을 zip 함수의 매개변수로 사용하고 결과를 목록 함수 아래에 넣습니다. 키 값 쌍은 목록의 튜플이 됩니다.
예시
Adict = {30:'Mon',11:'Tue',19:'Fri'}
# Given dictionary
print("The given dictionary: ",Adict)
# Using zip
Alist = list(zip(Adict.keys(), Adict.values()))
# Result
print("The list of tuples: ",Alist) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')] 추가
이 접근 방식에서 우리는 빈 목록을 취하고 모든 키 값 쌍을 튜플로 추가합니다. for 루프는 키 값 쌍을 튜플로 변환하도록 설계되었습니다.
예시
Adict = {30:'Mon',11:'Tue',19:'Fri'}
# Given dictionary
print("The given dictionary: ",Adict)
Alist = []
# Uisng append
for x in Adict:
k = (x, Adict[x])
Alist.append(k)
# Result
print("The list of tuples: ",Alist) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]