31

在发帖之前,我已经在 Python 中访问过字典中的任意元素,但对此我不确定。

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

4

8 回答 8

33

使用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)
于 2013-09-26T13:59:46.463 回答
13

如果使用 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+ 默认字典保留了插入顺序。文档中也提到了这一点:

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

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

于 2017-06-01T23:44:42.607 回答
2

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

编辑:

OP 澄清说,“第一个”和“最后一个”是指将键添加到字典中的顺序。 collections.OrderedDict应该适用于这种情况。

于 2013-09-26T13:53:48.520 回答
1

字典中没有“第一个”或“最后一个”键这样的东西,它不能保证任何特定的顺序。所以不可能得到“第一个”或“最后一个”元素。您只能围绕 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

有序字典就像普通字典一样,但它们会记住插入项目的顺序。当迭代一个有序字典时,项目按照它们的键被第一次添加的顺序返回。

于 2013-09-26T13:54:28.383 回答
1

With OrderedDict you can use iterators

d = OrderedDict(a=1, b=2, c=3)
next(iter(d)) # returns 'a'
next(reversed(d) # returns 'c'
于 2020-05-05T02:31:08.587 回答
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])

输出:-

第一个元素:- ('Key-3', 'Value-3')

最后一个元素:- ('Key-1', 'Value-1')

于 2018-09-04T09:35:18.590 回答
0

显然现在回答为时已晚,但我想在上面的精彩答案中添加以下内容

dct = {"first": 1, "second": 2, "last": 3}

first, *_, last = dct.items()
print("*** Items ***")
print("First Item:", first)
print("Last Item:", last)

first, *_, last = dct.keys()
print("*** Keys ***")
print("First Key:", first)
print("Last Key:", last)

first, *_, last = dct.values()
print("*** Values ***")
print("First Value:", first)
print("Last Value:", last)
*** Items ***
First Item: ('first', 1)
Last Item: ('last', 3)

*** Keys ***
First Key: first
Last Key: last

*** Values ***
First Value: 1
Last Value: 3
于 2021-11-29T19:05:52.440 回答
-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:"四", "蔓越莓":2, 3:"三", 2:"二", "Apple":3, 1:"一", "Bananna":1} dictionarySortingExample(sampleDictionary)

于 2013-09-26T14:30:46.250 回答