4

## [自學Python紀錄] HackerRank 新手30天挑戰-Day08

Hi there! 我是嘟嘟~受到前輩啟發，想說可以紀錄一下自己練習的過程，小女子為程式超超菜鳥，此系列非教學文，僅為個人解題筆記，可能有錯誤或未補充詳盡之處，歡迎前輩們不吝指教！也歡迎正在自學的夥伴一起討論學習～

## Day 8: Dictionaries and Maps（字典）

### 輸入格式

There are an unknown number of lines of queries. Each line (query) contains a `name` to look up, and you must continue reading lines until there is no more input.

### 樣本輸入

``````3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry
``````

### 樣本輸出

``````sam=99912222
harry=12299933
``````

### 我的解答(錯誤版本)

``````n = int(input())
phoneBook = {} #建立字典

for i in range(n):
name,phone = input().strip().split() #輸入n筆電話和姓名
phoneBook[name] = phone #新增字典資料[Key:value=name:phone]

for i in range(n):
nameTest = input() #輸入n筆測資
print(nameTest + '=' + phoneBook[nameTest]) if nameTest in phoneBook else print('Not found') #查詢姓名是否在電話簿裡面

``````

### 我的解答(修正後)

``````n = int(input())
phoneBook = {} #建立字典

for i in range(n):
name,phone = input().strip().split() #輸入n筆電話和姓名
phoneBook[name] = phone #新增n筆字典資料[key:value=name:phone]

for i in range(n):
while True: #因為不知道測資有幾筆，就一直跑迴圈
try:
nameTest = input() #嘗試讀取測資，沒有測資時會失敗，進入except
print(nameTest + '=' + phoneBook[nameTest]) if nameTest in phoneBook else print('Not found') #查詢姓名是否在電話簿裡面
except:
break #如果沒有測資了，跳出迴圈
``````

``````2
Ace 12345678
Luffy 87654321
Zoro
Nami
Usopp
Luffy
``````

``````Not found
Luffy=87654321
``````

## 補充:

### 建立字典

Python 創建字典的方式有兩種:

1. 使用大刮號 {}
2. 使用內建函數 dict()

``````movie_1 = {'name': 'Saving Private Ryan','year': 1998,'director': 'Steven Spielberg'}
movie_2 = dict(name='The Breakfast Club',year=1985,director='John Hughes')
``````