第7類:數組(Tuple)、集合(Set)以及詞典(Dictionary)

TQC+ 程式語言Python 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
 

程式碼:

def compute():
    Dict = {}
    while True:    
        key = input("Key: ")
        if key == 'end':
            return Dict
        value = input("Value: ")
        Dict[key] = value

print('Create dict1:')
dict1 = compute()

print('Create dict2:')
dict2 = compute()

dict1.update(dict2)
dict3 = sorted(dict1)

for row in dict3:
 print("%s: %s" %(row, dict1[row]))

 

TQC+ 程式語言Python 第7類:數組(Tuple)、集合(Set)以及詞典(Dictionary)





如果覺得文章內容還不錯的話,麻煩請幫我點個讚!感謝

可以多點幾次喔~~

第一次點讚需使用 Google 或 Facebook 帳號註冊

發表迴響取消回覆

Exit mobile version