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

时间:2013-09-26 13:51:01

标签: python

在发帖之前,我已经完成了Access an arbitrary element in a dictionary in Python,但我对此不确定。

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

8 个答案:

答案 0 :(得分:20)

使用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)

答案 1 :(得分:3)

如果使用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+默认字典保留了插入顺序。 documentation

中也提到了这一点
  

字典保留了广告订单。请注意,更新密钥不会影响订单。删除后添加的键将在末尾插入。

  

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

答案 2 :(得分:1)

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

编辑:

OP澄清说,“first”和“last”表示键被添加到字典中的顺序。 collections.OrderedDict适用于此案例。

答案 3 :(得分:1)

字典中没有“first”或“last”键,这不保证任何特定的排序。因此没有可能获得“第一”或“最后”元素。您只能在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 ]

虽然评论中指出已经有一个课程OrderedDicthttp://docs.python.org/2/library/collections.html#collections.OrderedDict

  

有序词典就像常规词典,但他们记得   插入项目的顺序。迭代一个有序的   字典,这些项目按照其键的顺序返回   加入。

答案 4 :(得分:0)

  

CPython实现细节:键和值以非随机的任意顺序列出,在Python实现中各不相同,并且取决于字典的插入和删除历史。 - dict documentation

但是我强烈建议不要依赖associative array数据结构中的项目顺序(dict就是其中之一),因为经常没有单一的明显方式来订购密钥。例如,在py "21" < "3"21 > 3

答案 5 :(得分: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:“four”,“Cranberry”:2,3:“three”,2:“two”,“Apple”:3,1:“one”,“Bananna”:1} dictionarySortingExample(sampleDictionary)

答案 6 :(得分:0)

您可以使用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])

输出:-

第一个元素:-(“键3”,“值3”)

最后一个元素:-(“键1”,“值1”)

答案 7 :(得分:0)

使用OrderedDict,您可以使用iterators

d = OrderedDict(a=1, b=2, c=3)
next(iter(d)) # returns 'a'
next(reversed(d) # returns 'c'