【问题标题】:How to access the first and the last elements in a dictionary?如何访问字典中的第一个和最后一个元素?
【发布时间】:2013-09-26 13:51:01
【问题描述】:

发帖之前,我已经通过Access an arbitrary element in a dictionary in Python,但我不确定。

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

【问题讨论】:

    标签: python dictionary


    【解决方案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 3.6 开始,不再需要 OrderDict(),因为当前的本机字典实现保留了插入顺序。
    • @juanIsaza 你能提供一个证明链接吗?!
    • 有没有办法做到这一点,而不必将整个字典内容复制到列表中?像 d.front() 和 d.back() 之类的东西?
    • @TechJS 我更新了他的答案,提供了文档链接和一些引用作为证明。
    【解决方案2】:

    如果使用 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 版中更改:保证字典顺序为插入顺序。这种行为是 CPython 3.6 的实现细节。

    【讨论】:

    • 依赖于订购的标准字典不一定安全:gandenberger.org/2018/03/10/ordered-dicts-vs-ordereddict
    • @fantabolous 当然,Pandas 和其他早于 Python3.6 的库不会假设任何顺序,但语言仍在不断发展,你应该接受新的做事方式,否则你会陷入过去最终你会失去生产力。
    【解决方案3】:

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

    编辑:

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

    【讨论】:

    • 我就是这么说的。有什么解决办法吗?
    • @user1162512 我已经添加了对键进行排序的建议,但这是你能做的最好的。
    • 如果我将字典存储为dict= {"xyz":294,"a":1,"rah":129} 会怎样。我将在什么基础上对密钥进行排序以获得 xyz 和 rah 的访问权限。
    • PS:我不想用 dict["xyz"] 搜索
    • @user1162512:你写{"xyz":294,"a":1,"rah":129}的第二个,你已经丢失了关于订单的任何信息,因为这是一个字典文字。如本主题其他地方所述,您可以使用 collections.OrderedDict 作为插入顺序变体。
    【解决方案4】:

    字典中没有“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

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

    【讨论】:

    • 或者使用collections.OrderedDict,如果它的“first”和“last”的定义与OP的一致。
    • 我将如何创建一个包装器?有演示吗?
    【解决方案5】:

    使用 OrderedDict,您可以使用 iterators

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

    【讨论】:

      【解决方案6】:

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

      【讨论】:

        【解决方案7】:

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

        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
        

        【讨论】:

          【解决方案8】:

          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)

          【讨论】:

            猜你喜欢
            • 2018-06-09
            • 1970-01-01
            • 2015-04-20
            • 2017-08-06
            • 2021-11-07
            • 2015-08-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多