새소식

Programming/Python

[Python] Dictionaries, Nesting

  • -

딕셔너리, 네스팅 및 시크릿 옥션

[파이썬 딕셔너리: 깊게 파보기]

파이썬의 딕셔너리는 실제 사전과 비슷하게 작동한다.

딕셔너리는 관련된 정보를 그룹화하고 태그를 달 수 있어서 매우 유용하다.

 

모든 딕셔너리는 두 부분으로 구성된다.

왼쪽에는 키가 있는데

이는 사전의 단어에 해당한다.

 

그리고 관련된 값이 있으며

이는 단어의 실제 정의에 해당한다.

 

파이썬에서 딕셔너리를 만드는 구문은 아래와 같다.

{Key: Value}

딕셔너리 구문을 만들기 위해서는 중괄호 세트를 사용한다.

중괄호 안에 있는 모든 것이 우리의 딕셔너리 내용이다.

 

키(Key)가 먼저 오고, 그 다음에 콜론(:)이 오고,

그 다음에 값(Value)이 온다.

 

위에 사진을 활용해서 딕셔너리를 만들어보면 아래와 같다.

{"Bug": "An error in a program that prevents the program from running as expected."}

이때, 딕셔너리에 하나 이상의 항목을 추가하고 싶다면 어떻게 할까?

 

각 키와 값 쌍을 쉼표로 구분한 다음 딕셔너리의 끝에 도달할 때까지 

키와 값 쌍을 계속 추가할 수 있다.

{
    "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 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."}

위 경우처럼 하나 이상의 요소가 있는 딕셔너리를 만들 때는,

더 쉽게 읽을 수 있도록 적절하게 형식을 갖추는 것이 중요하다.

 

따라서 파이썬 프로그래머들이 관례적으로 하는 일은

딕셔너리를 맨 위에 여는 중괄호로 시작하고

그 다음의 모든 항목은 한 번 들여쓰기를 하는 것이다.

그리고 그 항목의 끝에는 쉼표가 있다.

 

또 다른 좋은 방법은 딕셔너리나 리스트의 모든 항목을 쉼표로 끝맺는 것이다.

이렇게 하면 딕셔너리에 더 많은 항목을 추가해야 할 때

단순히 엔터를 누르고 다음 항목을 계속 입력할 수 있다.

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 again.",
}

딕셔너리에서 항목을 검색하고 싶다면 어떻게 할까?

 

리스트가 있다면 원하는 항목의 인덱스를 가져오면 될 일이다.

 

딕셔너리의 경우 구문 측면에서 유사하지만 유일한 차이점은 

딕셔너리는 키로 식별되는 요소를 가진다는 점이다.

 

예를 들어 Bug의 value를 원한다면

딕셔너리에 접근하고 대괄호 []를 추가하면 된다.

그리고 대괄호 안에 키를 제공할 것이다.

여기서 키는 문자열이고, 그 문자열은 "Bug"이다.

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 again.",
}
print(programming_dictionary["Bug"])

print를 하면 Bug의 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["Loop"] = "The action of doing something over and over again."

print(programming_dictionary)

이제 반대로,

전체 딕셔너리를 지우고 싶다면 어떻게 할까?

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 again."

print(programming_dictionary)

programming_dictionary = {}

print(programming_dictionary)

이럴 때는 간단하게 programming_dictionary를 빈 딕셔너리로 만들어주면 된다.


이번에는 딕셔너리의 항목을 수정해보자.

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 again."

programming_dictionary["Bug"] = "A moth in your computer."
print(programming_dictionary)

이렇게 하면 딕셔너리를 통해 이 키("Bug")를 가진 값을 찾아서 등호 오른쪽에 있는 값으로 할당할 것이다.

 

반면에, 해당 키를 가진 항목을 찾지 못하면 다시 등호 오른쪽에 있는 값으로 새로운 항목을 생성할 것이다.


마지막은 바로 딕셔너리를 반복하는 것이다.

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.",
}

for key in programming_dictionary:
	print(key)

이렇게 하고 출력하면 어떤 것이 print될까?

더보기

Bug

Function

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.",
}

for key in programming_dictionary:
    print(key) #키를 출력할 때
    print(programming_dictionary[key]) #value를 출력할 때

첫 번째 줄에서는 키가 출력되고,

두 번째 줄에서는 해당 키에 대한 값이 출력된다.


[실습]

시험 점수 매기기 프로그램

 

학생들의 시험 점수를 담은 딕셔너리 형식의 student_scores 데이터베이스에 접근할 수 있다.

student_scores의 키는 학생들의 이름이며 값은 그들의 시험 점수이다.

 

점수를 등급으로 변환하는 프로그램을 작성하자.

 

프로그램을 마치면 student_grades라는 새로운 딕셔너리가 있어야 한다.

이 딕셔너리는 학생 이름을 키로, 평가된 등급을 값으로 가져야 한다.

 

student_grades 딕셔너리의 최종 버전이 확인될 것이다.

 

점수 기준

-91-100점: 등급 = "Outstanding"

-81-90점: 등급 = "Exceeds Expectations"

-71-80점: 등급 = "Acceptable"

-70점 이하: 등급 = "Fail"

 

[답]

더보기

 

student_scores = {
    "Harry": 88,
    "Ron": 78,
    "Hermione": 95,
    "Draco": 75,
    "Neville": 60,
}

student_grades = {}
 
for students in student_scores:
    if student_scores[students] > 90:
        student_grades[students] = "Outstanding"
    elif student_scores[students] > 80:
        student_grades[students] = "Exceeds Expectations"
    elif student_scores[students] > 70:
        student_grades[students] = "Acceptable"
    else:
        student_grades[students] = "Fail"
 
print(student_grades)

[리스트와 딕셔너리 중첩하기]

딕셔너리에는 문자열이나 숫자 같은 단순한 값 대신에 리스트를 값으로 넣을 수도 있다.

마찬가지로, 딕셔너리를 값으로 사용할 수도 있다.

{
    Key: [List],
    Key2: {Dict},
}

이 경우, 우리는 첫 번째 키의 값으로 리스트를 가지고 있고,

두 번째 키의 값으로 딕셔너리를 가지고 있다.

 

딕셔너리 안에 딕셔너리가 중첩되면 구조가 조금 복잡해지기는 하지만,

더 복잡한 데이터를 저장하려고 할 때

더 많은 유연성을 제공한다.


이해를 위해 샘플 딕셔너리를 만들어보자.

capitals = {
    "France": "Paris",
    "Germany": "Berlin",
}

travel_log = {
    "France": ["Paris", "Lille", "Dijon"],
    "Germany": ["Stuttgart", "Berlin"],
}

이 코드에서 Lille을 어떻게 뽑아낼 수 있을까?

 

[답]

더보기
capitals = {
    "France": "Paris",
    "Germany": "Berlin",
}

travel_log = {
    "France": ["Paris", "Lille", "Dijon"],
    "Germany": ["Stuttgart", "Berlin"],
}

print(travel_log["France"][1])

우리는 이렇게 여러 층으로 구성된 nested_list를 만들 수 있다는 것을 보았다.

 

예를 들어, ["A", "B"] 라는 리스트가 있다면 인덱스 2에 리스트를 중첩할 수 있다.

nested_list = ["A", "B", ["C", "D"]]

 

이번에는 nested_list에서 문자 "D"를 출력하는 방법을 알아내자.

 

[답]

더보기
nested_list = ["A", "B", ["C", "D"]]

print(nested_list[2][1])

이제, 딕셔너리 안에 딕셔너리에 대해 알아보자.

capitals = {
    "France": "Paris",
    "Germany": "Berlin",
}

travel_log = {
    "France": {
        "num_times_visited": 8,
        "cities_visited": ["Paris", "Lille", "Dijon"],
        "total_visits": 12
    },
    "Germany": {
        "cities_visited": ["Berlin", "Hamburg", "Stuttgart"],
        "total_visites": 5
    },
}

이 travel_log에서 "Stuttgart"를 출력하는 방법은 무엇일까?

 

[답]

더보기
capitals = {
    "France": "Paris",
    "Germany": "Berlin",
}

travel_log = {
    "France": {
        "num_times_visited": 8,
        "cities_visited": ["Paris", "Lille", "Dijon"],
        "total_visits": 12
    },
    "Germany": {
        "cities_visited": ["Berlin", "Hamburg", "Stuttgart"],
        "total_visites": 5
    },
}

print(travel_log["Germany"]["cities_visited"][2])

 

'Programming > Python' 카테고리의 다른 글

[Python] Functions with Outputs  (0) 2024.12.03
[Python_Project] Secret Auction Program  (0) 2024.12.02
[Python] Function parameters & Caesar Cipher  (0) 2024.12.02
[Python] Python Functions & Karel  (0) 2024.12.01
[Python] Python Loops  (0) 2024.12.01
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.