在Python字典中实现键值对反转

12

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


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

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

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

4
{1: (a, b), 2: (c, d), 3: (e, f)}{1: (a, b), 3: (e, f), 2: (c, d)}中得到的结果一般来说是不同的,但这是否有意义? - RiaD
2
顺序是基于显示顺序还是数字键值?例如,如果原始字典为 {2: (a, b), 1: (c, d), 3: (e, f)},结果会是什么? - Barmar
5个回答

12

你只需要:

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是什么吗?我会在允许的时候立即接受这个答案。 - user14356245
1
@rishi 这里是 zip 的作用。为了举例说明,看一下 a = [1,2,3]; b = ['a','b','c']; print(list(zip(a, b))) - juanpa.arrivillaga
3
在Python 3.7之前,迭代顺序是不确定的,因此第二种方法可能会返回任意结果(但在这种情况下,问题可能就没有太多意义了)。 - Bernhard Barker

1

使用列表代替字典

假设你的键总是从1到N的整数,那么你的字典实际上应该是一个列表。而且无论你使用什么,都不应该将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')}
    

    0

    请尝试以下操作

    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')}


    0

    这应该能够实现所期望的结果。

    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')}
    

    -1
    你可以将原始字典的键与值进行压缩,由于您需要反转值,因此可以使用负步幅 [::-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')}
    

    1
    基本上与此前的答案相同。 - S3DEV
    @S3DEV 实际上,之前的回答没有我提供的内容。后来进行了编辑。 - Ann Zen

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接