投稿する前に、私は既にPython で辞書内の任意の要素にアクセスすることを経験しましたが、これについては確信が持てません。
長い辞書があり、その最初と最後のキーの値を取得する必要があります。dict[dict.keys()[0]]
andを使用しdict[dict.keys()[-1]]
て最初と最後の要素を取得できますが、キー:値のペアがランダムな形式で出力されるため (キー:値のペアの配置がランダムであるように)、このリンクで提供されるソリューションは常に機能しますか?
投稿する前に、私は既にPython で辞書内の任意の要素にアクセスすることを経験しましたが、これについては確信が持てません。
長い辞書があり、その最初と最後のキーの値を取得する必要があります。dict[dict.keys()[0]]
andを使用しdict[dict.keys()[-1]]
て最初と最後の要素を取得できますが、キー:値のペアがランダムな形式で出力されるため (キー:値のペアの配置がランダムであるように)、このリンクで提供されるソリューションは常に機能しますか?
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)
Python 辞書は順序付けされていないため、「最初」と「最後」は定義されていません。代わりに、キーを並べ替えてから、並べ替えられたセットの最初と最後のキーに関連付けられた要素にアクセスできます。
編集:
OPは、「最初」と「最後」とは、キーが辞書に追加された順序を意味することを明確にしました。 collections.OrderedDict
この場合はうまくいくはずです。
辞書には「最初」または「最後」のキーなどはなく、特定の順序は保証されません。したがって、「最初」または「最後」の要素を取得する可能性はありません。「最初」と「最後」のオブジェクトに関する情報を保存する、Python dict の周りに独自のラッパーのみを作成できます。
何かのようなもの
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 ]
コメントで指摘されたように、すでにクラスがありOrderedDict
ます:http://docs.python.org/2/library/collections.html#collections.OrderedDict
順序付き辞書は通常の辞書と同じですが、アイテムが挿入された順序を記憶しています。順序付けられたディクショナリを反復処理する場合、項目はキーが最初に追加された順序で返されます。
list() を使用してそれを行うことができます。
dir = dict()
dir['Key-3'] = 'Value-3' # Added First Item
dir['Key-2'] = 'Value-2' # Added Second Item
dir['Key-4'] = 'Value-4' # Added Third Item
dir['Key-1'] = 'Value-1' # Added Fourth Item
lst = list(dir.items()) # For key & value
# lst = list(dir.keys()) # For keys
# lst = list(dir.values()) # For values
print('First Element:- ', lst[0])
print('Last Element:- ', lst[-1])
出力:-
最初の要素:- ('Key-3', 'Value-3')
最後の要素:- ('Key-1', 'Value-1')
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:"4", "クランベリー":2, 3:"3", 2:"2", "りんご":3, 1:"1", "バナナ":1} dictionarySortingExample(sampleDictionary)