본문 바로가기
수업(국비지원)/Python

[Python] 컬렉션 - dictionary

by byeolsub 2023. 4. 24.

 📌

#### dictionary : {(key1:value1),(key2,value2),...}
score_dic = {'lee':100,'hong':70,'kim':90}
print(score_dic)
print(type(score_dic))

# hong의 점수 출력하기
# value <= dict['key']
score_dic['hong']

# hong 의 점수 75점으로 수정하기
score_dic['hong'] = 75
print(score_dic)

# park의 점수 80점으로 추가하기
score_dic['park']= 80
print(score_dic)

# park의 정보를 제거
del score_dic['park']
print(score_dic)

# 키 값들만 조회
print(score_dic.keys())
print(list(score_dic.keys()))

# 값들만 조회
print(score_dic.values()) # 중복 허용
print(list(score_dic.values()))

# 키와 값들의 쌍인 값으로 조회
print(score_dic.items())
print(list(score_dic.items()))

# dictionary 객체들을 반복문으로 조회
for n in score_dic : 
    # n : key 값
    print(n,"=",score_dic[n])
    
for n in score_dic.keys() :
    # n : key 값
    print(n,"=",score_dic[n]) 
    
for n,s in score_dic.items() :
    # n : key 값
    # s : value 값
    print(n,"=",s)    

for v in score_dic.items() :
    # v : 튜플객체. (k,v)쌍인 객체
    print(v[0],"=",v[1])    

for s in score_dic.values() : 
    print(s) # key 값을 조회 못함

'''
문제 : 1. 궁합음식의 키를 입력받아 해당되는 음식을 출력하기
         등록안된 경우 오류 발생. => 등록여부 판단필요
       2.종료 입력시 등록된 내용 출력하기
         등록된음식 :
              떡볶이 : 오뎅
              짜장면 : 단무지
       3. 등록이 안된 경우
          등록 여부를 입력받아, 등록하는 경우 궁합음식을 입력받기
          등록하시겠습니까(y)?
             y입력 : foods 객체에 추가. 
                    궁합 음식 입력받아서 foods에 추가함
             y가 아닌 경우 : 
                     음식을 다시 입력하기
'''
foods = {"떡볶이":"어묵","짜장면":"단무지","라면":"김치","맥주":"치킨"}
while True :
    myf = input(str(list(foods.keys()))+"중 입력(종료) :")
    if myf == '종료' : 
        break
    if myf in foods : # foods 데이터의 키값 중 myf값이 존재?  
       print("%s의 궁합음식: %s" % (myf,foods[myf]))
    else : 
        print("%s는 등록된 음식이 아닙니다." % myf)
        y = input("등록하시겠습니까?(y/n) :")
        # y.lower() : y 문자열을 소문자로 변경
        if y.lower() == 'y' :
            # myf2 : 입력된 궁합음식 값
            myf2 = input(myf + "의 궁합음식 입력:") # 궁합음식 입력
            foods[myf] = myf2  # (myf(키),myf2(값))
print("등록된 음식:")
for f in foods.items() :
    print(f[0],":",f[1])

📌

#### dictionary 데이터 생성하기
products = {"냉장고":220,"건조기":140,"TV":130,"세탁기":150,"컴퓨터":200}
# 200 미만의 제품만 product1 객체 저장하기
#1
product1 = {}
for k in products : 
    if products[k] < 200 :
       product1[k] = products[k]
print(product1)

#2       
product1 = {}
for k in products.keys() :
    if products[k] < 200 :
       product1[k] = products[k]
print(product1)
       
#3    
product1 = {}
for k,v in products.items() : # k = "냉장고" , v = 220
    if v < 200 : 
        product1[k] = v
print(product1)        

# 컨프리핸션 방식
#1
product2 = { k:v for k,v in products.items() if v < 200}
print(product2)

#2
product2 = { k:products[k] for k in products if products[k] < 200}
print(product2)

 

'수업(국비지원) > Python' 카테고리의 다른 글

[Python] 컬렉션 - set  (0) 2023.04.24
[Python] 컬렉션 - tuple  (0) 2023.04.24
[Python] 컬렉션 - list(리스트)  (0) 2023.04.24
[Python] 문자열 함수  (0) 2023.04.24
[Python] 중첩 반복문(별 찍기)  (0) 2023.04.24