【问题标题】:Reverse key value pairing in python dictionary [closed]python字典中的反向键值配对[关闭]
【发布时间】:2021-01-19 19:10:59
【问题描述】:

我需要一种方法来反转我的键值配对。让我说明一下我的要求。


dict = {1: (a, b), 2: (c, d), 3: (e, f)}

我希望将以上内容转换为以下内容:

dict = {1: (e, f), 2: (c, d), 3: (a, b)}

【问题讨论】:

  • 但这有意义吗?从{1: (a, b), 2: (c, d), 3: (e, f)} 和{1: (a, b), 3: (e, f), 2: (c, d)} 你通常会得到不同的结果
  • 排序是根据显示的顺序还是数字键值?例如。如果原始字典是{2: (a, b), 1: (c, d), 3: (e, f)},结果会是什么?

标签: python python-3.x dictionary


【解决方案1】:

你只需要:

new_dict = dict(zip(old_dict, reversed(old_dict.values())))

注意,在 Python 3.8 之前,dict_values 对象是不可逆的,您将需要类似:

new_dict = dict(zip(old_dict, reversed(list(old_dict.values()))))

【讨论】:

  • 谢谢你,这很好用。你能详细说明一下 zip 的作用吗?一旦允许,我会立即接受答案。
  • @rishi 这是zip 所做的。只是为了说明,看a = [1,2,3]; b = ['a','b','c']; print(list(zip(a, b)))
  • 在 Python 3.7 之前的迭代顺序不能保证,在这种情况下,第二种方法会返回任意结果(但在这种情况下,这个问题可能没有多大意义)。跨度>
【解决方案2】:

列表而不是字典

假设您的键始终是从 1 到 N 的整数,那么您的 dict 实际上应该是一个列表。而且无论你使用什么,你都不应该使用dict 作为变量名。

列表不会丢失任何信息:

d = {1: ('a', 'b'), 3: ('e', 'f'), 2: ('c', 'd')}
l = [v for k, v in sorted(d.items())]
# [('a', 'b'), ('c', 'd'), ('e', 'f')]

将索引移动 -1 也不会丢失任何信息。

取回信息

  • 您在l 中直接拥有排序后的值。

  • 如果您需要钥匙,您可以简单地调用:

range(len(l))
# range(0, 3)
  • 如果要索引i,可以拨打l[i]。
l[1] # Indices have been shifted. 2 is now 1
# ('c', 'd')
  • 如果您想要原始字典,您可以调用:
>>> dict(enumerate(l))
{0: ('a', 'b'), 1: ('c', 'd'), 2: ('e', 'f')}
>>> dict(enumerate(l, 1))
{1: ('a', 'b'), 2: ('c', 'd'), 3: ('e', 'f')}
  • 为了得到反转的值,您可以简单地反转列表:
>>> l[::-1]
[('e', 'f'), ('c', 'd'), ('a', 'b')]
>>> l[::-1][0]
('e', 'f')

并且,为了回答您最初的问题,如果您真的想要保留建议的数据格式,您可以致电:

>>> dict(list(enumerate(l[::-1])))
{0: ('e', 'f'), 1: ('c', 'd'), 2: ('a', 'b')}
>>> dict(list(enumerate(l[::-1], 1)))
{1: ('e', 'f'), 2: ('c', 'd'), 3: ('a', 'b')}

【讨论】:

    【解决方案3】:

    这应该会达到预期的结果。

    def rev_keys(d: dict) -> dict:
        '''Return dictionary structure with the 
            keys reasigned in opposite order'''
        old_keys = list(d.keys())
        new_keys = old_keys[::-1]
        nd = {}
        for ki in range(len(new_keys)):
            nd[new_keys[ki]]= d[old_keys[ki]]
        return nd
    

    给定和输入看起来像:

    dt = {'1': ('a','b'), '2': ('c','d'), '3': ('e','f')}
    
    rev_keys(dt)
    

    返回:

    {'3': ('a', 'b'), '2': ('c', 'd'), '1': ('e', 'f')}
    

    【讨论】:

      【解决方案4】:

      试试下面的

      dict_ = {1: ('a','b'), 2: ('c','d'), 3: ('e','f')}
      values = [y for x, y in dict_.items()][::-1]
      res = {}
      for x, y in enumerate(dict_.items()):
          res[y[0]] = values[x]
      
      print(res)
      

      这是输出:

      {1: ('e', 'f'), 2: ('c', 'd'), 3: ('a', 'b')}

      【讨论】:

        【解决方案5】:

        您可以使用原始字典的值压缩原始字典的键,并且由于您希望将值反转,您可以使用负跨步[::-1]。

        注意dict.values()不能下标,因此需要先将其转换为列表:

        dct = {1: ('a', 'b'), 2: ('c', 'd'), 3: ('e', 'f')}
        dct = dict(zip(dct, list(dct.values())[::-1]))
        print(dct)
        

        输出:

        {1: ('e', 'f'), 2: ('c', 'd'), 3: ('a', 'b')}
        

        【讨论】:

        • 与this earlier answer的答案基本相同。
        • @S3DEV 实际上,之前的答案没有我给出的答案。然后被编辑了。
        猜你喜欢
        • 2018-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-13
        • 1970-01-01
        • 2016-10-09
        • 2022-01-25
        相关资源
        最近更新 更多