본문 바로가기
코딩 연습/코딩배우기

[python] dict 연습 - 단어(문장)에서 모음 찾기

by good4me 2020. 10. 8.

goodthings4me.tistory.com

 

■ [dict 연습] 단어, 문장에서 영어 모음 찾기

vowels = ['a', 'e', 'i', 'o', 'u']
word = input('Provides a word to search for vowels: ')

found = []
found_dict = {}

for kv in vowels:
    found_dict[kv] = 0 # dict 0으로 초기화

for letter in word:
    if letter in vowels:
        if letter not in found: # found list에 철자가 없으면
            found.append(letter)
        found_dict[letter] += 1 # 철자 맞으면 1 증가


# 입력한 단어, 문장의 모음 리스트
print( 'vowels in the word that you provided:', end=' ')  # 'end='로 연결
for vowel in found:
    print(vowel, end=', ')


# dict 출력 방법
print('\n\n-- key에 맞는 value 출력 --')
for k in found_dict:
    print(k, 'was found', found_dict[k], 'time(s)')

print('\n\n-- 내장함수 sorted 사용 --')
for k in sorted(found_dict): 
    print(k, 'was found', found_dict[k], 'time(s)')

print('\n\n-- items() 키/값 목록 반환 --')
for k, v in found_dict.items(): # sorted(found_dict.items())
    print(k, 'was found', v, 'item(s)')



[실행 결과]

Provides a word to search for vowels: If you want to be happy
vowels in the word that you provided: o, u, a, e, 

-- key에 맞는 value 출력 --
a was found 2 time(s)
e was found 1 time(s)
i was found 0 time(s)
o was found 2 time(s)
u was found 1 time(s)


-- 내장함수 sorted 사용 --
a was found 2 time(s)
e was found 1 time(s)
i was found 0 time(s)
o was found 2 time(s)
u was found 1 time(s)


-- items() 키/값 목록 반환 --
a was found 2 item(s)
e was found 1 item(s)
i was found 0 item(s)
o was found 2 item(s)
u was found 1 item(s)

good4me.co.kr

# dict 초기화 시키기
fruits = {}

while True:
    word = input('insert fruits name: ')
    if word == 'exit':
        break
    
    # dict 초기화 시키기 : in 사용
    # if word in fruits:
    #     fruits[word] += 1
    # else:
    #     fruits[word] = 1


    # dict 메서드 setdefault( , ) 사용
    fruits.setdefault(word, 0) # 필요시 0 초기화
    fruits[word] += 1

for fruit, num in fruits.items():
    print('{} = {}개'.format(fruit, fruits[fruit]))

 

[참고] Head First Python

 

댓글