1. Dictionary
- 딕셔너리는 키(key)와 값(value)이 한 쌍이 하나의 대응 관계를 가지고 있는 자료형 입니다.
- 예를 들면 "김씨" : "여자", "박씨" : "남자" 이런식으로 "김씨"라는 Key가 열쇠고 그 "김씨"의 값으로 "여자"라는 것이 쌍을 이루는 자료형 입니다.
딕셔너리 = { 키: 값 }
딕셔너리 = { Key1: Value1, Key2: Value2, Key3: Value3, Key4: Value4}
ex)
programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.", // key1: value1
"Function": "A piece of code that you can easily call over and over again.",// key2 : value2
}
2. 리스트와 딕셔너리 중첩
- 딕셔너리의 기본 형태는 {key: value}이지만 value의 값에 단순한 값을 넣는 것이 아니라, 리스트나 딕셔너리를 넣을 수 있다.
- 즉, 딕셔너리에서 중첩이란 그 안에 다른 리스트나, 딕셔너리를 넣는 것을 말한다.
ex) 딕셔너리 안의 리스트
travel_log = {
"France": ["Paris", "Lille", "Dijon"],
"Germany": ["Berlin", "Hamburg", "Stuttgart"],
}
ex) 딕셔너리 안의 딕셔너리
travel_log = [
{
"country": "France",
"cities_visited": ["Paris", "Lille", "Dijon"],
"total_visits": 12,
}
1) 실습예제
Exercise) 해당 코드는 수정하지 않고 중간에 코드를 추가하여 travel_log에 딕셔너리를 추가하는 코드를 작성하세요(단, 함수를 정의하여 그 함수를 사용해 추가해야합니다.)
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)
Solution)
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
def add_new_country(country, visits, cities):
new_country = {}
new_country["country"] = country
new_country["visits"] = visits
new_country["cities"] = cities
travel_log.append(new_country)
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)
'Python Study' 카테고리의 다른 글
Python Study(return) (0) | 2023.03.08 |
---|---|
Python Study(함수 정의 및 호출 응용) (0) | 2023.03.02 |
Python Study(반복문(While)) (0) | 2023.02.18 |
Python Study(함수 정의 및 호출/들여쓰기) (0) | 2023.02.18 |
Python Study(반복문(for)) (0) | 2023.02.05 |