Python 如何访问字典中的第一个和最后一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19030179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access the first and the last elements in a dictionary?
提问by PythonEnthusiast
Before posting, I have already gone through Access an arbitrary element in a dictionary in Python, butI'm uncertain about this.
在发布之前,我已经在 Python 中访问了字典中的任意元素,但是我对此不确定。
I have a long dictionary and I've to get the values of its first and last keys. I can use dict[dict.keys()[0]]
and dict[dict.keys()[-1]]
to get the first and last elements, but since the key:value pairs are outputted in a random form(as in the positioning of the key:value pairs is random), will the solution provided in this link always work?
我有一本很长的字典,我必须获取它的第一个和最后一个键的值。我可以使用dict[dict.keys()[0]]
和dict[dict.keys()[-1]]
来获取第一个和最后一个元素,但是由于键:值对以随机形式输出(如键:值对的定位是随机的),此链接中提供的解决方案是否始终有效?
采纳答案by óscar López
Use an OrderedDict
, because a normal dictionary doesn't preserve the insertion order of its elements when traversing it. Here's how:
使用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)
回答by Codie CodeMonkey
Python dictionaries are unordered, so "first" and "last" isn't defined. Instead, you can sort your keys, and then access the element associated with the first and last key in your sorted set.
Python 字典是无序的,因此没有定义“first”和“last”。相反,您可以对键进行排序,然后访问与排序集中的第一个和最后一个键关联的元素。
EDIT:
编辑:
The OP clarified that by "first" and "last" he meant the order in which keys were added to the dictionary. collections.OrderedDict
should work for this case.
OP 澄清说,“第一个”和“最后一个”是指将键添加到字典中的顺序。 collections.OrderedDict
应该适用于这种情况。
回答by lejlot
There is no such thing as "first" or "last" key in dictionary, which does not guarantee any particular ordering. So there is no possibilityto get "first" or "last" element. You can only create your own wrapper around python dict, which will store the information about "first" and "last" object
字典中没有“第一个”或“最后一个”键这样的东西,它不能保证任何特定的顺序。所以不可能获得“第一个”或“最后一个”元素。您只能围绕 python dict 创建自己的包装器,它将存储有关“第一个”和“最后一个”对象的信息
Something like
就像是
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 ]
Although as it was pointed out in the comment there is already a class OrderedDict
: http://docs.python.org/2/library/collections.html#collections.OrderedDict
虽然正如评论中指出的那样,已经有一个类OrderedDict
:http: //docs.python.org/2/library/collections.html#collections.OrderedDict
Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
有序字典就像普通字典一样,但它们记住插入项目的顺序。迭代有序字典时,项目将按照它们的键首次添加的顺序返回。
回答by Stonewall_Jefferson
def dictionarySortingExample(yourDictionary):
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)
example dictionary sorting
示例字典排序
sampleDictionary = {4:"four", "Cranberry":2, 3:"three", 2:"two", "Apple":3, 1:"one", "Bananna":1} dictionarySortingExample(sampleDictionary)
sampleDictionary = {4:"four", "Cranberry":2, 3:"three", 2:"two", "Apple":3, 1:"one", "Bananna":1} dictionarySortingExample(sampleDictionary)
回答by juan Isaza
If working with Python 3.6+ you can do a one liner:
如果使用 Python 3.6+,你可以做一个单行:
First:
第一的:
list({'fist': 1, 'second': 2, 'last': 3}.items())[0]
=> ('first', 1)
Last:
最后的:
list({'fist': 1, 'second': 2, 'third': 3}.items())[-1]
=> ('third', 1)
This is the case because Python 3.6+ default dictionary preserves insertion order. This is also mentioned in the documentation:
这是因为 Python 3.6+ 默认字典保留插入顺序。文档中也提到了这一点:
Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.
字典保留插入顺序。请注意,更新密钥不会影响顺序。删除后添加的键插入最后。
and
和
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
在 3.7 版更改: 字典顺序保证是插入顺序。此行为是 3.6 中 CPython 的实现细节。
回答by Niraj Phutane
You can do it by using list().
您可以使用 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])
Output:-
输出:-
First Element:- ('Key-3', 'Value-3')
第一个元素:- ('Key-3', 'Value-3')
Last Element:- ('Key-1', 'Value-1')
最后一个元素:- ('Key-1', 'Value-1')