【问题标题】:Reversing the order of key-value pairs in a dictionary (Python) [duplicate]反转字典中键值对的顺序(Python)[重复]
【发布时间】:2015-11-13 14:53:43
【问题描述】:

如何在 Python 中反转字典键值对的顺序?例如,我有这本字典:

{"a":1, "b":2, "c":3}

我想把它倒过来让它返回:

{"c":3, "b":2, "a":1}

有没有我没听说过的功能可以做到这一点?一些代码行也很好。

【问题讨论】:

    标签: python dictionary reversing


    【解决方案1】:

    字典没有任何顺序感,因此您的键/值对不以任何格式排序。

    如果你想保留键的顺序,你应该从一开始就使用collections.OrderedDict,而不是使用普通的字典,示例-

    >>> from collections import OrderedDict
    >>> d = OrderedDict([('a',1),('b',2),('c',3)])
    >>> d
    OrderedDict([('a', 1), ('b', 2), ('c', 3)])
    

    OrderedDict 将保留键输入字典的顺序。在上述情况下,它将是列表中存在的键的顺序 - [('a',1),('b',2),('c',3)] - 'a' -> 'b' -> 'c'

    然后你可以使用 reversed(d) 获得键的相反顺序,示例 -

    >>> dreversed = OrderedDict()
    >>> for k in reversed(d):
    ...     dreversed[k] = d[k]
    ...
    >>> dreversed
    OrderedDict([('c', 3), ('b', 2), ('a', 1)])
    

    【讨论】:

    • 是的,正确,这不是重点,它的排序会排序它,OP不想sort,OP想要逆序的键。
    • 这不适用于 Python 3.6 及更高版本。字典现在保持秩序
    【解决方案2】:

    字典使用 Hashmap 来存储 Key 和对应的值。

    看:Is a Python dictionary an example of a hash table?

    任何与哈希相关的东西都没有顺序。

    你可以这样做:

    d = {}
    d['a']=1
    d['b']=2
    d['c']=3
    d['d']=4
    print d
    for k,v in sorted(d.items(),reverse = True):
        print k,v
    

    d.items() 返回一个元组列表:[('a', 1), ('c', 3), ('b', 2), ('d', 4)]k,v 获取元组中的值以循环迭代。 sorted() 返回一个排序列表,而您不能 use d.items().sort() 不返回,而是尝试覆盖 d.items()

    【讨论】:

      【解决方案3】:

      这会奏效。 基于 Venkateshwara 的“原样”对我不起作用。

      def reverse(self):
          a = self.yourdict.items()
          b = list(a) # cast to list from dict_view
          b.reverse() # actual reverse
          self.yourdict = dict(b) # push back reversed values
      

      【讨论】:

        【解决方案4】:
        d={"a":1, "b":2, "c":3}
        x={}
        for i in sorted(d.keys(),reverse=True):
            x[i]=d[i]
        print(x)
        

        【讨论】:

          【解决方案5】:
          #The dictionary to be reversed
          dict = {"key1":"value1","key2":"value2","key3":"value3"}
          
          #Append the keys of the dictionary in a list
          list_keys = []
          for k in dict.keys():
              list_keys.append(k)
          
          rev_dict = {}
          #Traverse through the reversed list of keys and add them to a new dictionary
          for i in reversed(list_keys):
              rev_dict[i] = dict[I]
          print(rev_dict)
          
          #OUTPUT: {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-01-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多