TQC+ 程式語言 Python 3 _ 708 詞典合併

說明:
請撰寫一程式,自行輸入兩個詞典(以輸入鍵值"end"作為輸入結束點,詞典中將不包含鍵值"end"),將此兩詞典合併,並根據key值字母由小到大排序輸出,如有重複key值,後輸入的key值將覆蓋前一key值。

輸入與輸出會交雜如下,輸出的部份以粗體字表示
Create dict1:
Key: a
Value: apple
Key: b
Value: banana
Key: d
Value: durian
Key: end
Create dict2:
Key: c
Value: cat
Key: e
Value: elephant
Key: end
a: apple
b: banana
c: cat
d: durian
e: elephant


Alt text

程式碼:
dict1, dict2 = {}, {}

print('Create dict1:')
liKey1 = input('Key: ')
while liKey1 != "end":
    dict1[liKey1] = input('Value: ')
    liKey1 = input('Key: ')

print('Create dict2:')
liKey2 = input('Key: ')
while liKey2 != "end":
    dict2[liKey2] = input('Value: ')
    liKey2 = input('Key: ')

dict1.update(dict2)

for i in sorted(dict1.keys()): print(i,": ",dict1[i],sep='')

沒有留言:

張貼留言