티스토리 뷰

반응형

9강 요약

9강에서는 딕셔너리의 개념과 리스트 중첩(Nesting)에 대한 개념에 대해서 배웠다. 딕셔너리는 여러 아이템들을 한 단위로 감싸 관리한다는 점에서 리스트와 굉장히 유사한 개념이다. 딕셔너리 안에 값을 추가, 제거, 수정 등을 할 수 있다는 점에서도 리스트와 동일하게 동작한다. key와 value로 구성되는 딕셔너리 형태 안에는 리스트가 중첩되어 들어갈 수도 있는데, 따라서 데이터를 저장하는데 있어서 더 다양한 선택지를 제공한다. 이를 이용해 다양한 예제로 코딩 연습도 하였다. 

 

1. 딕셔너리(Dictionaries)

파이썬의 딕셔너리는 실제 사전(dictionaries)과 비슷한 방식으로 동작한다. 사전을 이용해 모르는 단어나 개념의 의미를 찾아보듯이, 파이썬의 딕셔너리도 특정한 개념(key)과 그 개념을 설명하는 정보(value)들로 구성된다. 

1) 딕셔너리 만들기 

#기본 형식
{Key: Value}

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

 

2) 딕셔너리는 여러개의 key와 value로 구성될 수 있다. 

따라서 언제라도 다양한 key, value 값을 입력할수 있도록 마지막 value값의 끝에 숨표(,)를 붙여놓으면 편리하다. 

{
"Bug": "An error in a program that prevents the program from running as expected.", 
"Loop": "The action of doing sth over and over again.",
}

 

3) 딕셔너리의 특정값을 불러올 수 있다. 

작동하는 방식은 기존에 배웠던 리스트에서 인덱스를 활용하여 특정 요소를 호출하는 것과 유사하다. 

중요한 것은 딕셔너리에서 값을 불러올때 'key'값을 정확하게 입력해야한다. 

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 sth over and over again.",

}

print(programming_dictionary["Bug"])

 

4) 딕셔너리에 신규 key, value를 추가할 수 있다. 

programming_dictionary["Function"] = "A piece of code that you can easily call over and over again."

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 sth over and over again.'}

 

5) 기타 딕셔너리와 관련된 여러가지 문법들

#빈 딕셔너리 생성하기
empty_dict = {}

#기존 딕셔너리의 모든 값 초기화하기
programming_dictionary = {}
print(programming_dictionary)

#기존 딕셔너리의 특정 키의 value 수정하기
programming_dictionary["Bug"] = "A moth in your computer."
print(programming_dictionary)

 

6) 딕셔너리로 반복문 생성하기

리스트의 반복문과 다른 점은 단순히 for item in dictionary: 과 같이 item만 반복하는 경우, 딕셔너리의 'key' 값만 반복된다는 점이다. 

따라서 딕셔너리의 실제 value들을 반복하기 위해선 아래와 같이 작성해야 한다. 

#loop through a dictionary
for key in programming_dictionary:
    print(key)  #<- key값만 반복됨
    print(programming_dictionary[key]) #<-value 값이 반복되는 방법

 

2. 중첩(Nesting)

리스트 중첩, 딕셔너리 중첩 등에 대해 배웠다. 

딕셔너리 안에 리스트를 중첩시킬 수도 있고, 리스트 안에 딕셔너리를 중첩시킬 수도 있다. 

한줄에 한꺼번에 작성하게 되면 데이터가 늘어날수록 여러 괄호들 때문에 이해하기 쉽지 않다. 

따라서 적절하게 줄바꿈을 해주면 좋다. 

#Nesting a List in a Dictionary

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

#Nesting Dictionary in a Dictionary

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

#Nesting Dictionaries in Lists

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

 

3. 실습: 리스트 속 딕셔너리 중첩

리스트 안에 딕셔너리가 요소로 들어가는 중첩 방식에 대해 실습을 진행했는데, 익혀두면 꽤나 유용할 것 같아서 예제 실습 후 코드 비교를 해보았다. 짧은 코드이므로 내가 작성한 것과 안젤라 선생님이 작성한 것에서 큰 차이는 없더라도 분명 다른 점이 있기 때문에 좋은 부분은 꼭 배워서 새겨두려고 하자! 

 

1) 내가 작성한 코드

country = input() # Add country name
visits = int(input()) # Number of visits
list_of_cities = eval(input()) # create list from formatted string

travel_log = [
  {
    "country": "France",
    "visits": 12,
    "cities": ["Paris", "Lille", "Dijon"]
  },
  {
    "country": "Germany",
    "visits": 5,
    "cities": ["Berlin", "Hamburg", "Stuttgart"]
  },
]
# Do NOT change the code above 👆

# TODO: Write the function that will allow new countries
# to be added to the travel_log. 
# 내가 작성한 부분

def add_new_country(country, visits, cities):
  new_country = {
    "country": country, 
    "visits": visits,
    "cities": list_of_cities
  }
  travel_log.append(new_country)

# Do not change the code below 👇
add_new_country(country, visits, list_of_cities)
print(f"I've been to {travel_log[2]['country']} {travel_log[2]['visits']} times.")
print(f"My favourite city was {travel_log[2]['cities'][0]}.")

 

2) 안젤라선생님 코드

country = input() # Add country name
visits = int(input()) # Number of visits
list_of_cities = eval(input()) # create list from formatted string
travel_log = [
  {
    "country": "France",
    "visits": 12,
    "cities": ["Paris", "Lille", "Dijon"]
  },
  {
    "country": "Germany",
    "visits": 5,
    "cities": ["Berlin", "Hamburg", "Stuttgart"]
  },
]
# Your code here 👇
# 안젤라 선생님 코드
def add_new_country(name, times_visited, cities_visited):
  new_country = {}
  new_country["country"] = name
  new_country["visits"] = times_visited
  new_country["cities"] = cities_visited
  travel_log.append(new_country)

add_new_country(country, visits, list_of_cities)
print(f"I've been to {travel_log[2]['country']} {travel_log[2]['visits']} times.")
print(f"My favourite city was {travel_log[2]['cities'][0]}.")

 

 안젤라 선생님은 우선 'new_country'라는 빈 딕셔너리를 생성해둔 후, 각 key와 value를 정의해준 방식이라면, 나는 'new_country'라는 딕셔너리를 생성함과 동시에 그 안에 들어갈 key와 value를 한번에 정의하였다. 내 코드는 딕셔너리의 형상을 한눈에 볼 수 있다는 특징이 있고, 안젤라 선생님의 방식은 좀 더 체계적이라는 특징이 있는 것 같다. 결국 마지막에 append 함수를 이용해 추가해준 방식은 동일하다.