我需要一种反转键值对的方法。让我说明一下我的要求。
dict = {1: (a, b), 2: (c, d), 3: (e, f)}
我希望将上述内容转换为以下内容:
dict = {1: (e, f), 2: (c, d), 3: (a, b)}
我需要一种反转键值对的方法。让我说明一下我的要求。
dict = {1: (a, b), 2: (c, d), 3: (e, f)}
我希望将上述内容转换为以下内容:
dict = {1: (e, f), 2: (c, d), 3: (a, b)}
你只需要:
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()))))
a = [1,2,3]; b = ['a','b','c']; print(list(zip(a, b)))
- juanpa.arrivillaga假设你的键总是从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')]
你可以直接在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')}
请尝试以下操作
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')}
这应该能够实现所期望的结果。
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')}
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: (a, b), 2: (c, d), 3: (e, f)}
和{1: (a, b), 3: (e, f), 2: (c, d)}
中得到的结果一般来说是不同的,但这是否有意义? - RiaD{2: (a, b), 1: (c, d), 3: (e, f)}
,结果会是什么? - Barmar