10 python dictionary python-3.x
我需要一种方法来反转我的键值配对。让我来说明我的要求。
dict = {1: (a, b), 2: (c, d), 3: (e, f)}
Run Code Online (Sandbox Code Playgroud)
我希望将上述内容转换为以下内容:
dict = {1: (e, f), 2: (c, d), 3: (a, b)}
Run Code Online (Sandbox Code Playgroud)
jua*_*aga 11
您只需要:
new_dict = dict(zip(old_dict, reversed(old_dict.values())))
Run Code Online (Sandbox Code Playgroud)
请注意,在 Python 3.8 之前,dict_values 对象不可逆,您将需要类似以下内容:
new_dict = dict(zip(old_dict, reversed(list(old_dict.values()))))
Run Code Online (Sandbox Code Playgroud)