【发布时间】:2021-01-24 22:08:03
【问题描述】:
我需要反转一个字典,这样每个旧值现在都将成为一个键,而旧键将成为新值。
诀窍是旧字典中可能有多个相同的值,所以我需要新字典中的每个值都是一个列表,如果旧字典中有相同的值,那么它们都将在新字典的值列表。
例如: 字典 {"python" : 1, "is" : 1, "cool" : 2}
最终会变成:{1 : ["python", "is"], 2 : ["cool"]}
这是我尝试过的:
def inverse_dict(my_dict):
new_dict = {}
values_list = list(my_dict.values())
new_dict = new_dict.fromkeys(values_list)
for key in new_dict:
new_dict[key] = []
for old_key in my_dict:
new_dict[my_dict[old_key]] = list(new_dict[my_dict[old_key]]).append(old_key)
return new_dict
非常感谢对我的方法(以及解决问题的更好方法)的任何帮助,因为我对 Python 非常陌生,谢谢!
【问题讨论】:
-
这能回答你的问题吗? In-place dictionary inversion in Python
标签: python dictionary