2013-09-26 70 views
8

在發佈之前,我已經通過了Access an arbitrary element in a dictionary in Python,但我對此不確定。如何訪問字典python中的第一個和最後一個元素?

我有一個很長的字典,我必須得到它的第一個和最後一個鍵的值。我可以使用dict[dict.keys()[0]]dict[dict.keys()[-1]]來獲取第一個元素和最後一個元素,但是由於鍵值對以隨機形式輸出(如鍵值的定位是隨機的),所以此鏈接中提供的解決方案始終工作?

回答

16

使用OrderedDict,因爲普通字典在遍歷元素時不會保留其元素的插入順序。具體方法如下:

# import the right class 
from collections import OrderedDict 

# create and fill the dictionary 
d = OrderedDict() 
d['first'] = 1 
d['second'] = 2 
d['third'] = 3 

# retrieve key/value pairs 
els = list(d.items()) # explicitly convert to a list, in case it's Python 3.x 

# get first inserted element 
els[0] 
=> ('first', 1) 

# get last inserted element 
els[-1] 
=> ('third', 3) 
+2

從Python 3.6開始,OrderDict()不再是必需的,因爲當前的本地字典實現保留了插入順序。 –

+0

@juanIsaza你能提供一個證明鏈接嗎?! – TechJS

+0

有沒有辦法做到這一點,而不必將整個字典內容複製到列表中?類似d.front()和d.back()? – Mattia

1

Python詞典是無序的,所以「first」和「last」沒有定義。相反,您可以對鍵進行排序,然後訪問與排序集中第一個和最後一個鍵相關聯的元素。

編輯:

的OP澄清說,「第一」和「最後」他的意思是在哪個鍵添加到字典中的順序。 collections.OrderedDict應該適用於這種情況。

+0

那就是我說的。有沒有解決方案? – PythonEnthusiast

+0

@ user1162512我已經添加了一個排序鍵的建議,但這是你能做的最好的。 –

+0

如果我把我的字典存爲'dict = {「xyz」:294,「a」:1,「rah」:129}'會怎麼樣?爲了得到xyz和rah的訪問權限,我會在什麼基礎上對鍵進行排序。 – PythonEnthusiast

1

字典中沒有「第一個」或「最後一個」鍵,它不保證任何特定順序。所以有不可能得到「第一」或「最後」元素。您只能創建圍繞蟒字典自己的包裝,這將存儲有關的「第一」和「最後一個」對象

喜歡的東西

class MyDict: 

    def __init__(self): 
    self.first=None 
    self.last=None 
    self.dict={} 

    def add(key, value): 
    if self.first==None: self.first=key 
    self.last=key 
    self.dict[key]=value 

    def get(key): 
    return self.dict[key] 

    def first(): 
    return self.dict[ self.first ] 

    def last(): 
    return self.dict[ self.last ] 

雖然,因爲它是在註釋中指出已經有信息一類OrderedDicthttp://docs.python.org/2/library/collections.html#collections.OrderedDict

有序詞典就像是普通的字典,但他們還記得 的項目插入的順序。當遍歷一個有序的 字典時,這些項目將按照它們的密鑰添加的第一個 的順序返回。

+4

或者使用''collections.OrderedDict'',如果它的「first」和「last」的定義與OP的定義一致。 – fjarri

+0

我將如何創建一個包裝?任何演示? – PythonEnthusiast

0

CPython的實現細節:鍵和值列在其中的非隨機的,不同的Python實現不同而不同,取決於插入和刪除的字典的歷史以任意順序。 - dict documentation

不過我強烈建議不依賴於associative array數據結構項目的順序(字典是其中之一),因爲經常有命令鍵沒有一個單一的明顯的方式。例如python "21" < "3"21 > 3

0

DEF dictionarySortingExample(yourDictionary):

#get all the keys and store them to a list 
allKeys = yourDictionary.keys() 

#sort the list of keys 
allKeysSorted = sorted(allKeys) 

#retrieve the first and last keys in the list 
firstKey = allKeysSorted[0] 
lastKey = allKeysSorted[-1] 

#retrive the values from the dictionary 
firstValue = yourDictionary[firstKey] 
lastValue = yourDictionary[lastKey] 

print "---Sorted Dictionary---" 
print "original dictionary: " + str(yourDictionary) 
print "list of all keys: " + str(allKeys) 
print "ordered list of all keys: " + str(allKeysSorted) 
print "first item in sorted dictionary: " + str(firstKey) + ":" + str(firstValue) 
print "last item in sorted dictionary: " + str(lastKey) + ":" + str(lastValue) 

示例字典排序

sampleDictionary = {4: 「四」, 「蔓越莓」:2,3: 「三」 ,2:「two」,「Apple」:3,1:「one」,「Bananna」:1} dictionarySortingExample(sampleDictionary)

0

如果使用Python 3.6+,你可以做一行代碼:

第一:

list({'fist': 1, 'second': 2, 'last': 3}.items())[0] 
=> ('first', 1) 

末:

list({'fist': 1, 'second': 2, 'third': 3}.items())[-1] 
=> ('third', 1) 

這是因爲Python 3.6或更高版本默認的字典保留插入順序的情況。

相關問題