gpt4 book ai didi

python-3.x - 将字典反转为键 : list of values?

转载 作者:行者123 更新时间:2023-12-03 16:15:04 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Reverse / invert a dictionary mapping

(32 个回答)


6天前关闭。




如何转换python字典d = {1:10, 2:20, 3:30, 4:30}{10: [1], 20: [2], 30: [3, 4]} ?

我需要反转一个字典,值应该成为另一个字典的键,并且值应该是列表中的键,即也在排序的问题中。

最佳答案

在 python dict 中反转键和值有点棘手。您应该记住,python dict 必须有 unique键。

因此,如果您知道在反转当前字典的键和值时将具有唯一键,则可以使用简单的 dict comprehension像这个例子:

{v:k  for k,v in my_dict.items()}

但是,您可以使用 groupby来自 itertools像这个例子的模块:
from itertools import groupby

a = {1:10, 2:20, 3:30, 4:30}
b = {k: [j for j, _ in list(v)] for k, v in groupby(a.items(), lambda x: x[1])}
print(b)

>>> {10: [1], 20: [2], 30: [3, 4]}

关于python-3.x - 将字典反转为键 : list of values?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44851342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com