[udemy] Python 부트캠프 : 100개의 프로젝트로 Python 개발 완전 정복을 통해 학습하고 있습니다.
딕셔너리(Dictionaries)
- 'key: value' 형태로 중괄호로 묶어서 사용함.
- 하나 이상의 요소가 이는 딕셔너리를 만들 때는 쉽게 읽을 수 있도록 만드는 것이 중요함.
= 딕셔너리를 맨 위에 여는 중괄호를 사용하고 그 다음의 모든 항목은 한 번 들여쓰기를 함.
다음 항목이 있어 항목의 끝에 쉼표가 있을 때, 다음 항목이 다음 줄로 이동하도록 함.
마지막 중괄호는 딕셔너리의 시작과 일치하는 위치에 있어야 함.
programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again."
}
- 또 다른 방법은 딕셔너리나 리스트의 모든 항목을 쉼표로 끝맺는 것
- 이렇게 하면 딕셔너리에 더 많은 항목을 추가해야 할 때, 그냥 엔터를 치고 다음 항목을 계속 입력할 수 있음.
딕셔너리 출력
- 딕셔너리는 키로 식별되는 요소를 가짐.
- 딕셔너리를 출력하고 싶을 때, 딕셔너리를 호출하고 대괄호([])를 추가하고, 대괄호 안에 키를 넣으면 됨.
= 키는 문자열이고, 키를 넣을 때는 정확하게 철자를 잘 넣어야 함. (오타를 내는 것이 아주 흔한 실수)
- 딕셔너리에서도 존재하지 않는 키를 출력하려고 하면, 오류가 발생함.
- 딕셔너리를 정의할 때 각 키에 문자열을 넣지 않으면, 선언된 변수로 인식하게 됨.
programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again.",
"Loop": "The action of doing something over and over agin."
}
print(programming_dictionary["Bug"])
# 결과
An error in a program that prevents the program from running as expected.
딕셔너리 항목 추가
- 딕셔너리 항목을 추가하고 싶을 때, 딕셔너리를 호출하고 다시 대괄호를 사용하여 키를 정의하고 등호 뒤에 =로 값을 할당함.
- 항목 추가 후에 출력을 해보면 마지막에 Loop가 추가된 것을 확인할 수 있음.
programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again.",
}
# 딕셔너리 추가
programming_dictionary["Loop"] = "The action of doing something over and over agin."
# 딕셔너리 출력
print(programming_dictionary)
# 결과
{'Bug': 'An error in a program that prevents the program from running as expected.', 'Function': 'A piece of code that you can easily call over and over again.', 'Loop': 'The action of doing something over and over agin.'}
딕셔너리 삭제
- 딕셔너리 리스트는 아무것도 없는 대괄호를 사용하여 만들 수 있음.
- 빈 딕셔너리로 만들고 싶을 때, 딕셔너리를 호출하고 대괄호만 사용하면 출력할 때 비어있는 것을 확인할 수 있음.
programming_dictionary = {}
print(programming_dictionary)
# 결과
(출력 결과 없음)
딕셔너리 수정
- 딕셔너리 value를 수정하고 싶으면, 딕셔너리를 호출하고 키 값을 넣은 뒤 등호 뒤에 =를 사용하여 내용을 수정함.
- 만약 기존 키가 없다면, Value를 가지고 새로운 항목을 생성함.
programming_dictionary["Bug"] = "A moth in your computer."
print(programming_dictionary)
# 결과
{'Bug': 'A moth in your computer.', 'Function': 'A piece of code that you can easily call over and over again.', 'Loop': 'The action of doing something over and over agin.'}
딕셔너리 반복
- 딕셔너리를 반복하려면, for 문 등을 사용해 출력할 수 있는데 기본 적으로 key 값만 출력함.
- value 값도 함께 출력하고 싶다면, print 문을 한 번 더 사용해서 딕셔너리[변수]로 출력하면 됨.
programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again.",
"Loop": "The action of doing something over and over agin."
}
for thing in programming_dictionary:
print(thing)
print(programming_dictionary[thing])
# 결과
Bug
An error in a program that prevents the program from running as expected.
Function
A piece of code that you can easily call over and over again.
Loop
The action of doing something over and over agin.
실습: 시험 점수 매기기 프로그램
학생들의 시험 점수를 담은 딕셔너리 형식의 student_scores 데이터베이스에 접근할 수 있습니다. student_scores의 키는 학생들의 이름이며 값은 그들의 시험 점수입니다.
점수를 등급으로 변환하는 프로그램을 작성해주세요.
프로그램을 마치면 student_grades라는 새로운 딕셔너리가 있어야 합니다. 이 딕셔너리는 학생 이름을 키로, 평가된 등급을 값으로 가져야 합니다.
student_grades 딕셔너리의 최종 버전이 확인될 것입니다.
**절대** 기존 student_scores 딕셔너리를 변경하지 않도록 lines 1-7을 수정하지 마세요.
다음은 점수 기준입니다:
- 91 - 100점: 등급= "Outstanding"
- 81 - 90점: 등급= "Exceeds Expectations"
- 71 - 80점: 등급= "Acceptable"
- 70점 이하: 등급= "Fail"
# Default
student_scores = {
'Harry': 88,
'Ron': 78,
'Hermione': 95,
'Draco': 75,
'Neville': 60
}
student_grades = {
# Code
student_scores = {
'Harry': 88,
'Ron': 78,
'Hermione': 95,
'Draco': 75,
'Neville': 60
}
student_grades = {
'Harry': "Exceeds Expectations",
'Ron': "Acceptable",
'Hermione': "Outstanding",
'Draco': "Acceptable",
'Neville': "Fail"
}
print(student_grades)
(음, 이렇게 쉽게 통과하는게 맞는건가...)
중첩(Nesting)
- 여러 개의 키와 값 쌍을 딕셔너리에 추가할 수 있으며, 이때 값에 리스트를 값으로 넣을 수 있음.
- 반대로 딕셔너리를 값 쌍으로도 사용할 수 있음.
{
key: [List],
key2: {Dict},
}
❓ Qusetion
Q1. See if you can figure out how to print out "Lille" from the nested List called travel_log.
travel_log = {
"France": ["Paris", "Lille", "Dijon"],
"Germany": ["Stuttgart", "Berlin"]
}
print(travel_log["France"][1])
# 결과
Lille
Q2. Do you remember how to get items that are nested deeply in a list? Try to print "D" from the list nested_list.
nested_list = ["A", "B", ["C", "D"]]
print(nested_list[2][1])
# 결과
D
Q3. Figure out how to print out "Stuttgart" from the following list.
travel_log = {
"France": {
"cities_visited": ["Paris", "Lille", "Dijon"],
"total_visits": 8,
},
"Germany": {
"cities_visited": ["Stuttgart", "Berlin", "Hamburg"],
"total_visits": 5
}
}
print(travel_log["Germany"]["cities_visited"][0])
# 결과
Stuttgart
9일차 프로젝트
비밀 경매 프로그램과 순서도
from art import logo
print(logo)
def compare_people(blind_recodes):
highest = 0
winner = ""
for bid in blind_recodes:
new = blind_recodes[bid]
if new > highest:
highest = new
winner = bid
print(f"The winner is {winner} with a bid of ${highest}.")
blind_auction = {}
continue_question = True
while continue_question:
name = input("What ia your name?: ")
price = int(input("What's your bid? $ "))
blind_auction[name] = price
type = input("Are there any other bidders? Type 'yes' or 'no'. \n").lower()
if type == 'no':
continue_question = False
compare_people(blind_auction)
elif type == 'yes':
print("\n" * 20)
'Language > Python' 카테고리의 다른 글
[Section8] 함수의 매개변수와 카이사르 암호 (1) | 2025.01.16 |
---|---|
[Section7] 게임 프로젝트(행맨) (0) | 2025.01.14 |
[Section6] 파이썬 함수와 카렐 (0) | 2025.01.13 |
[Section5] 파이썬 반복문 (0) | 2025.01.13 |
[Section4] 파이썬 리스트 (0) | 2025.01.12 |