Python程式:獲取字典的第一個和最後一個元素


Python是一種解釋型、面向物件、高階程式語言,具有動態語義。由Guido Van Rossum於1991年開發。它支援多種程式設計正規化,包括結構化、面向物件和函數語言程式設計。在深入探討主題之前,讓我們首先回顧一下與所提供問題相關的基本概念。

字典是一組唯一、可變且有序的專案。字典使用花括號書寫,包含鍵和值:鍵名可用於引用字典物件。資料值以鍵值對的形式儲存在字典中。

有序和無序的含義

當我們將字典稱為有序時,我們的意思是內容具有不會改變的設定順序。無序專案缺乏明確的順序,因此無法使用索引查詢特定專案。

示例

請參閱以下示例,以便更好地理解上述概念。

請注意,字典鍵區分大小寫;名稱相同但大小寫不同的鍵將被不同地處理。

Dict_2 = {1: 'Ordered', 2: 'And', 3: 'Unordered'}
print (Dict_2)

輸出

{1: 'Ordered', 2: 'And', 3: 'Unordered'}

示例

請參閱以下示例,以便更好地理解概念

Primary_Dict = {1: 'Grapes', 2: 'are', 3: 'sour'}
print("\nDictionary with the use of Integer Keys is as following: ")
print(Primary_Dict)

# Creating a Dictionary

# with Mixed keys
Primary_Dict = {'Fruit': 'Grape', 1: [10, 22, 13, 64]}
print("\nDicionary with the use of Mixed Keys is as following: ")
print(Primary_Dict)

輸出

Dictionary with the use of Integer Keys is as following:
{1: 'Grapes', 2: 'are', 3: 'sour'}
Dictionary with the use of Mixed Keys:
{'Fruit': 'Grape', 1: [10, 22, 13, 64]}

在使用Python時,有很多情況下我們需要獲取字典的第一個鍵。這可以用於許多不同的具體用途,例如測試索引或更多此類用途。讓我們來看一些完成這項工作的方法。

使用list()類+ keys()

可以使用上述技術的組合來執行此特定任務。在這裡,我們只是從完整字典中keys()收集的鍵建立一個列表,然後只訪問第一個條目。在使用此方法之前,您只需要考慮一個因素,那就是它的複雜性。透過迭代字典中的每個專案,它將首先將整個字典轉換為列表,然後再提取其第一個成員。這種方法的複雜度將為O(n)。

透過使用list()類獲取字典中的最後一個鍵,例如last_key = list(my_dict)[-1]。list類將字典轉換為鍵列表,可以透過訪問索引-1處的元素來獲取最後一個鍵。

示例

請參閱以下示例以更好地理解

primary_dict = {
   'Name': 'Akash',
   'Rollnum': '3',
   'Subj': 'Bio'
}
last_key = list(primary_dict) [-1]
print (" last_key:" + str(last_key))
print(primary_dict[last_key])
first_key = list(primary_dict)[0]
print ("first_key :" + str(first_key))

輸出

last_key: Subj
Bio
first_key :Name

示例

以下程式建立一個名為Primary_dict的字典,其中包含五個鍵值對。然後,它將整個字典列印到螢幕上,然後分別打印出字典的第一個和最後一個鍵。

primary_dict = {'Grapes' : 1, 'are' : 2, 'sour' : 3, 'and' : 4, 'sweet' : 5} print ("The primary dictionary is : " + str(primary_dict)) res1 = list (primary_dict.keys())[0] res2 = list (primary_dict.keys())[4] print ("The first key of the dictionary is : " + str(res1)) print ("the last key of the dictionary is :" + str(res2))

輸出

The primary dictionary is : {'Grapes': 1, 'are': 2, 'sour': 3, 'and': 4, 'sweet': 5}
The first key of the dictionary is : Grapes
the last key of the dictionary is : sweet

示例

如果您只需要字典的第一個鍵,一種有效的方法是使用`next()`和`iter()`函式的組合。`iter()`函式用於將字典條目轉換為可迭代物件,而`next()`則獲取第一個鍵。此方法的複雜度為O(1)。請參閱以下示例以更好地理解。

primary_dict = {'Grapes' : 1, 'are' : 2, 'sour' : 3, 'and' : 4, 'sweet' : 5}
print ("The primary dictionary is : " + str(primary_dict))
res1 = next(iter(primary_dict))
print ("The first key of dictionary is as following : " + str(res1))

輸出

The primary dictionary is : {'Grapes': 1, 'are': 2, 'sour': 3, 'and': 4, 'sweet': 5}
The first key of dictionary is as following : Grapes

結論

在本文中,我們解釋了兩種從字典中查詢第一個和最後一個元素的不同示例。我們還編寫了一個程式碼,透過使用next()+ iter()來查詢字典中僅有的第一個元素。

更新於:2023年4月24日

18K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.