dictionary 기본 원리
{"key": "value"}
programming_dictionary = {"a":"b", "c":"d"}
print(programming_dictionary)
# output
# {"a":"b", "c":"d"}
print(programming_dictionary["a"])
# output
# b
아래의 input 값을 기존 리스트 내에 딕셔너리로 추가하기
#input
Brazil
2
["Sao Paulo", "Rio de Janeiro"]
함수와 매개변수를 이용하여 리스트 내에 새로운 딕셔너리 추가
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"]
},
]
def add_new_country(new_country, new_visits, new_list_of_cities):
#혼동이 없도록 parameter를 입력값과 다른, 새로운 값으로 지정해준다.
new_travel_log = {}
new_travel_log["country"] = new_country
new_travel_log["visits"] = new_visits
new_travel_log["cities"] = new_list_of_cities
travel_log.append(new_travel_log)
# print(travel_log)
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]}.")
=> 리스트 안에 새로운 값을 추가해주는 것과 동일한 방식 ('.append' 사용)
#output
I've been to Brazil 2 times.
My favourite city was Sao Paulo.
'python' 카테고리의 다른 글
[python] return 이해하기 (0) | 2024.06.02 |
---|---|
[python] #연습문제 - 비밀 경매 프로그램 생성기 (0) | 2024.06.02 |
[python] #연습문제 - caesar code 생성하기 (0) | 2024.06.01 |
[python] 소수 찾기 (0) | 2024.06.01 |
[python] #행맨 게임 (4) - 정답에 없는 값을 입력하였을 때 목숨을 하나 잃도록 하기 (0) | 2024.06.01 |