TOP
class="layout-aside-left paging-number">
본문 바로가기
[파이썬 Projects]/<파이썬 기초>

[파이썬] 파이썬 기초 - 딕셔너리 보완

by 기록자_Recordian 2025. 1. 21.
728x90
반응형
딕셔너리 이전 내용
 

[파이썬] 파이썬기초: 자료형 - 딕셔너리 자료형

시작에 앞서해당 내용은 ' 박응용 지음. 이지스 퍼블리싱' 을 토대로 작성되었습니다. 보다 자세한 내용은 해당 서적에 상세히 나와있으니 서적을 참고해 주시기 바랍니다. 자료형 자료형이란

puppy-foot-it.tistory.com


딕셔너리 보완

 

  • 딕셔너리의 키를 한 줄씩 출력하려면 print(*딕셔너리 변수명, sep="\n")
  • 딕셔너리의 요소 삭제하려면 딕셔너리 변수명.pop(삭제할 요소명)
  • if 요소명 in 딕셔너리명: (딕셔너리에 해당 요소가 있는지 여부 출력 boolean 자료형으로) > 그에 따라 조건문 나머지 완성하면 됨.
  • 딕셔너리에 키 추가하기: 딕셔너리명[추가할 키(key)] = 추가할 값(value)
  • 딕셔너리의 특정 키의 value 수정하기: 딕셔너리명[추가할 value의 key] = 수정할 value
  • 딕셔너리의 데이터를 한 줄씩 for문으로 출력하기: for key, value in dictionary.items()
  • 딕셔너리 내포:  {키:값 for 키 in 딕셔너리}
  • 딕셔너리 내포 + 조건문:  {키:값 for 키 in 딕셔너리 if 조건문}
  • values의 원소를 {원소:"원소"} 형태인 딕셔너리로 생성하기: {x:str(x) for in dictionary(또는 리스트)}

관련 예제 및 코드

# pprint 라이브러리 활용하면 "key":"value" 쌍으로 한 줄씩 출력가능
from pprint import pprint

dic = {
    "name" : "pey",
    "phone" : "01112341234",
    "birth" : "1115"
    }

# 딕셔너리 출력하기
print(dic) # {'name': 'pey', 'phone': '01112341234', 'birth': '1115'}

# 딕셔너리의 키를 한 줄씩 출력하기
print(*dic, sep="\n")
pprint(dic) # {'birth': '1115', 'name': 'pey', 'phone': '01112341234'}

dic_a = {1: "hi"}
dic_b = {"a": [1, 2, 3]}

print(dic_a) # {1: 'hi'}
print(dic_b) # {'a': [1, 2, 3]}

# 딕셔너리의 요소 삭제하기
# 딕셔너리의 dic에서 'birth' 삭제하기
print(dic.pop("birth"))
print(dic)

# 삭제가 이미 되었기 때문에 오류
# print(dic.pop("birth"))

# 키 값 지우기
# del dic["phone"]
# print(dic)

# 키 값 확인하여 삭제하기
if "birth" in dic:
    print("birth가 있어요")
    del dic["birth"]
    print(dic)

else:
    print("birth는 key로 존재하지 않아요")

# 딕셔너리에 키 추가하기
dic["birth"] = "20001205"
print(dic)

# 기존에 있던 key 수정
dic['phone'] = "01011114444"
print(dic)

# 딕셔너리의 데이터를 한 줄씩 for문으로 출력하기
for key, value in dic.items():
    print(f"{key}: {value}")


# Q. 딕셔너리 내포
values = range(1, 7)
# values의 원소가 짝수일 경우 {원소:제곱} 형태인 딕셔너리로 생성 
result = {x:x**2 for x in values if x % 2 == 0}
print(result) # {2: 4, 4: 16, 6: 36}

# values의 원소를 {원소:"원소"} 형태인 딕셔너리로 생성
dic = {i:str(i) for i in values}
print(dic) # {1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6'}

# fruits의 원소를 {원소:원소의 길이} 형태인 딕셔너리로 생성
fruits = ["apple", "mango", "orange"]
dict = {x:len(x) for x in fruits}
print(dict) # {'apple': 5, 'mango': 5, 'orange': 6}

# Q. 단어 카운트 만들기
text_data = "Create the highest, grandest vision possible for your life,\
    because you become what you believe"

# 답1
text_dict = text_data.split()
text_dict = {x:x.count(x) for x in text_dict}
print(text_dict)

# 답2
for x in text_dict:
    print(f"{x}의 등장횟수 = {x.count(x)}회")

 

이러한 방법도 있다.

count_dict = {}
text_dict = text_data.split()
for x in text_dict:
    if x in count_dict:
        count_dict[x] += 1
    else:
        count_dict[x] = 1
print(count_dict)

for key, value in count_dict.items():
    print(f"{key}의 등장횟수: {value}")

  • 먼저 count_dict 라는 딕셔너리를 만들고
  • text_data를 공백으로 나눠 단어를 나눈 뒤 text_dict 변수에 저장
  • text_dict를 반복문으로 돌려서 단어가 딕셔너리 내에 있다면 1을 더해주고, 그렇지 않다면 1을 대입하는데, for 반복문이 돌면서 중복인 단어의 경우 노출 횟수마다 1을 더하게 된다.
  • 그리고나서 count_dict를 출력하면 딕셔너리 형태로 출력되는데,
  • 이를 한 줄로 출력하게 만들기 위해 for 반복문 + 딕셔너리.items() 로 돌려서 print문을 사용해 한 줄씩 출력한다.

다음 내용

 

[파이썬] 파이썬 기초 - 파일 복사, 디렉토리

파일 복사하기 input으로 불러올 파일과 저장할 파일명을 받은 뒤,불러온 파일의 내용을 저장할 파일에 그대로 복사할 수 있다.# 파일 복사하기infileName = input("입력 파일 이름: ")outfileName = input("

puppy-foot-it.tistory.com

 

728x90
반응형