본문 바로가기

Python

Python - 딕셔너리 연습

member_list = ["lee","hong","kim"]
data_list = ["lee",100,"Seoul",90,member_list]
print(member_list)
print(data_list)
print(type(member_list))
print(type(data_list))

# member_list 첫번째 요소를 'aaa' 변경하기
member_list[0] = 'aaa'
print(member_list)
print(data_list)

# member_list, data_list의 요소의 갯수 출력하기
print(len(member_list)) #3
print(len(data_list)) #5

# data_list의 요소 중 member_list의 요소의 갯수 출력하기
print(len(data_list[4])) #3

# member_list에 'park' 요소 추가하기
member_list.append("park")
print(member_list)
print(data_list)

# member_list에 'park' 요소 1번 인덱스에 추가하기
member_list.insert(1,'park')
print(member_list)
print(data_list)

# member_list에 'park' 요소를 삭제하자 # 앞에 있는 순서대로 park 지워짐
member_list.remove('park')
print(member_list)
print(data_list)

# member_list에 1번 인덱스의 데이터를 삭제하기
del member_list[1]
print(member_list)
print(data_list)

member_list = ["park","lee","hong","kim"]
data_list = ["lee",100,"Seoul",90,member_list]

# member_list를 정렬하기
member_list.sort()
print(member_list)
print(data_list)

member_list.sort(reverse=True)
print(member_list)
print(data_list)

# member_list를 역순하기
member_list.reverse()
print(member_list)
print(data_list)

# data_list에서 member_list 데이터 중 kim을 출력하기
data_list[4][1]

# 딕셔너리 키,값
member_list = {'lee':100,'hong':70,'kim':90}
print(member_list)

print(type(member_list))
print(len(member_list))

#dictionary의 값을 조회하기
print(member_list["hong"])

#dictionary의 값을 추가하기
member_list["park"] = 80
print(member_list)

member_list["park"] = 70
print(member_list)
print(member_list['park'])

#dictionary의 값을 변경하기
member_list["park"]=70
print(member_list)
print(member_list['park'])

#dictionary의 값을 제거하기
del member_list["park"]
print(member_list)

#딕셔너리의 모든 키와 값을 출력하기
print(member_list)

#딕셔너리의 모든 키를 출력하기
print(member_list.keys())

#딕셔너리의 모든 값을 출력하기
print(member_list.values())

#딕셔너리의 모든 키와 값을 출력하기
print(member_list.items())

singer = {} #딕셔너리 데이터로 지정
singer['이름'] = "트와이스"
singer['구성원수'] = 9
singer['데뷔곡'] = '우아하게'
singer['소속사'] = 'JYP'
singer

#키값만 조회하기
singer.keys()

#밸류값만 조회하기
singer.values()

#모두 조회하기
singer.items()

#키들만 조회하기
print(singer.keys())
for i in singer.keys():
    print("%s=>%s" % (i,singer[i]))
    
#키와 값 모두 조회하기
for i in singer.items():
    print(i)
    print("%s=>%s" %(i[0],i[1]))

#딕셔너리에 키가 존재 여부
print('이름' in singer)
print('히트곡' in singer)
print('데뷔곡' in singer)

foods = \
{"떡볶이":"오뎅","짜장면":"단무지","라면":"김치","맥주":"치킨"}
foods

for i in foods.keys() : 
    print("%s=>%s" % (i,foods[i]))

#화면에서 궁합음식으로 등록된 값을 입력받아 해당되는 음식을 출력하는
#프로그램 작성하기
#입력된 음식이 등록되지 않은 경우는 등록된 음식이 아닙니다.
#결과 출력하고, 등록 여부를 입력받아(y) foods 객체에 값을 추가하기
#단 입력은 종료값이 입력될 때까지 계속 입력 받기 

foods[input("음식 입력 : ")]
print(input("음식 입력 : ") in foods)

a = input("음식 입력 :")
if a in foods :
    print(foods[a])
elif a not in foods :
    print("등록된 음식이 아닙니다.")

while True:
    myfood = input(str(list(foods.keys())) + "중 음식이름을 입력하세요 :")
    if myfood == "종료" :
        break
    if myfood in foods : 
        print(("<%s> 궁합음식은 <%s>입니다.") % (myfood,foods[myfood]))
    else :
        print("등록된 음식이 아닙니다.")
        yn = input("좋아하는 음식으로 등록하시겠습니까?(y) : ")
        if yn.lower() == 'y':
            f = input("궁합음식을 입력하세요 : ")
            foods[myfood] = f
print("프로그램 종료")

# 딕셔너리 데이터 정렬하기
import operator
dic,list = {},[]
dic = {"Thomas":"토마스","Edward":"에드워드","Henry":"헨리",
       "Gothen":"고든","James":"제임스"}
print(dic.items())

# 튜플 중 첫번째 데이터를 기준으로 정렬 : itemgetter(0)
# reverse = True : 내림차순 정렬
list = sorted(dic.items(),key=operator.itemgetter(0),reverse=True)
print(list)


# 영문 이름으로 오름차순 정렬하기 
list = sorted(dic.items(),key=operator.itemgetter(0))
print(list)


# 한글 이름으로 오름차순 정렬하기 : itemgetter(1)
list = sorted(dic.items(),key=operator.itemgetter(1))
print(list)

# 튜플 
tp1 = (10,20,30)
print(tb1)
print(tp1[0])
tp1[0] = 100 #값 변경불가

#tp1.append(40) 요소 추가 
list1 = list(tp1)
list1.append(40)
print(list1)
tp1 = tuple(list1)
print(tp1[0])
tp1[0] = 100 #값 변경불가