리스트에 딕셔너리 추가하는 함수 만들기

2022. 11. 27. 12:12Trip to Python

 

유데미 강의에서 리스트에 딕셔너리를 추가하는 함수를 만드는 문제가 나왔다. 미진했던 부분들을 복습해보고자 한다.
 
<처음 시도한 잘못짠 코드>
 
travel_log = [
{
  "country""France",
  "visits"12,
  "cities": ["Paris""Lille""Dijon"]
},
{
  "country""Germany",
  "visits"5,
  "cities": ["Berlin""Hamburg""Stuttgart"]
},
]
#🚨 Do NOT change the code above
 
- 리스트 안에 딕셔너리가 있고 3개의 키에 각각 벨류가 담겨 있다.

#TODO: Write the function that will allow new countries
#to be added to the travel_log. 👇
new_addition = {}
def add_new_country(country, times, where):
    new_addition["countries"] = country * 파라미터 스펠링 오류!
    new_addition["visits"] = times
    new_addition["cities"] = where
    list.travel_log += new_addition * list에 원소 추가 함수 잘못 코딩!

#🚨 Do not change the code below
add_new_country("Russia"2, ["Moscow""Saint Petersburg"])
print(travel_log)

- 문제는 리스트에 딕셔너리를 넣는 함수를 만드는 것으로 새로운 딕셔너리에 각 파라미터에 해당하는 값을 넣어주어서 딕셔너리의 내용을 넣어주고 리스트 원소 추가 함수를 사용하여 완성한다.

 

 

<정답 코드>

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, times, where):
    new_addition = {}
    new_addition["country"] = country
    new_addition["visits"] = times
    new_addition["cities"] = where
    travel_log.append(new_addition)

#🚨 Do not change the code below
add_new_country("Russia"2, ["Moscow""Saint Petersburg"])
print(travel_log)

- 파라미터에 "" 붙이지 않는 것에 유의하고 list.append(추가 원소)의 활용법을 잘 알아두어야한다. 물론 스펠링 오류는 항상 유의해야만 한다. 또한 함수 안에 빈 딕셔너리를 넣는 것 또한 유의해야한다.