如何访问字典中的第一个和最后一个元素?

问题描述 投票:10回答:7

发布之前,我已经经历过Access an arbitrary element in a dictionary in Python,但是对此我不确定。

我有一本很长的字典,我必须获取它的第一个和最后一个键的值。我可以使用dict[dict.keys()[0]]dict[dict.keys()[-1]]来获取第一个和最后一个元素,但是由于key:value对是以随机形式输出的(如key:value对的位置是随机的),请提供解决方案在此链接中始终有效吗?

python dictionary
7个回答
20
投票

使用OrderedDict,因为普通字典在遍历时不会保留其元素的插入顺序。方法如下:

OrderedDict

4
投票

如果使用Python 3.6+,则可以使用一个衬里:

第一:

# 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)

最后:

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

之所以如此,是因为Python 3.6+默认字典保留了插入顺序。 list({'fist': 1, 'second': 2, 'third': 3}.items())[-1] => ('third', 1) 中也提到了这一点:

字典保留插入顺序。请注意,更新密钥不会影响顺序。删除后添加的密钥将插入到末尾。

在版本3.7中更改:保证字典顺序为插入顺序。此行为是3.6版CPython的实现细节。


1
投票

在字典中没有“第一”或“最后”键之类的东西,它不保证任何特定的顺序。因此,没有[[不可能获得“第一个”或“最后一个”元素。您只能围绕python dict创建自己的包装器,该包装器将存储有关“第一个”和“最后一个”对象的信息]类似

documentation

尽管已在注释中指出,但已经有一个类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

有序词典就像普通词典一样,但它们记住插入项目的顺序。当遍历有序字典,则按其键的先后顺序返回项已添加。

1
投票
Python字典是无序的,因此未定义“第一”和“最后”。相反,您可以对键进行排序,然后访问与排序集中的第一个键和最后一个键关联的元素。

0
投票
def dictionarySortingExample(yourDictionary):

0
投票
您可以使用list()来完成。

-1
投票
CPython实现细节:键和值以任意顺序列出,该顺序是非随机的,在Python实现中会有所不同,并且取决于字典的插入和删除的历史记录。 -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])
© www.soinside.com 2019 - 2024. All rights reserved.