반응형

 

 

 

딕셔너리

days_in_month = {
    #여기에 코드를 완성해 보세요.
    '1월' : 31,
    '2월' : 28,
    '3월' : 31
 }

print(days_in_month['2월'])

-> 28

 

 

딕셔너리의 이름표에는 문자열과 숫자형, 튜플을 사용할 수 있으며, 값으로는 어떤 자료형이 오던 상관 없습니다.

#            ↓ 이름표는 문자열 또는 숫자를 주로 사용하지만
dict = {     "이름표"    :    [1,2,3] }
#                           ↑ 값은 리스트를 포함해서 무엇이든 올 수 있습니다.

print( dict["이름표"] )

결과

[1, 2, 3]

 

 

 

 

딕셔너리 수정하기

  • 추가

    dict['three'] = 3

  • 수정

    dict['one'] = 11

  • 삭제

    del(dict['one'])

    dict.pop('two')

 

 

딕셔너리 Key와 Value 값 출력하기

days_in_month = {"1월":31, "2월":28, "3월":31, "4월":30, "5월":31}

for key in days_in_month.keys():
    print(key)
    
for value in days_in_month.values():
    print(value)

출력

1월
2월
3월
4월
5월
31
28
31
30
31

 

days_in_month = {"1월":31, "2월":28, "3월":31, "4월":30, "5월":31}

for key, value in days_in_month.items():
    #출력 형식은 아래 print함수를 참고하세요
    print("{}은 {}일이 있습니다.".format( key, value ) )

출력

1월은 31일이 있습니다.
2월은 28일이 있습니다.
3월은 31일이 있습니다.
4월은 30일이 있습니다.
5월은 31일이 있습니다.

 

 

 

인덱스를 이용하는 방법

products = {"풀" : 1800, "색종이" : 1000}

for product in products.items():
    print("{}은 {}원이다.".format(product[0], product[1]))

 

 

 

리스트와 딕셔너리 비교

 

 

 

값 확인

def check_and_clear(box):
    if "불량품" in box.keys():
        box.clear()
    
box1 = {"불량품" : 10}
check_and_clear(box1)
# {}가 출력되어야합니다.
print(box1)

box2 = {"정상품": 10}
check_and_clear(box2)
# {"정상품": 10}가 출력되어야합니다.
print(box2)

 

딕셔너리 합치기

products = {"풀":800, "딱풀":1200, "색종이":1000,"색연필":5000,"스케치북":3500}
catalog = {"겨울용 실내화":12000, "색종이":8000, "딱풀":1400}

products.update(catalog)

print(products)
{'풀': 800, '딱풀': 1400, '색종이': 8000, '색연필': 5000, '스케치북': 3500, '겨울용 실내화': 12000}

 

 

 

 

 

 

반응형

+ Recent posts