gpt4 book ai didi

python - 基于重复值合并字典

转载 作者:行者123 更新时间:2023-11-28 21:29:09 25 4
gpt4 key购买 nike

我有一个这样设置的字典

{
"key1" : [1,2,4],
"key2" : [2,4],
"key3" : [1,2,4],
"key4" : [2,4],
....
}

我想要的是这样的东西。

[
[
["key1", "key3"],
[1,2,4],
],
[
["key2", "key4"],
[2,4],
],
.....
]

基于唯一值对的键和值列表。我怎样才能以Pythonic的方式做到这一点?

最佳答案

您可以像这样反转字典:

orig = {
"key1" : [1,2,4],
"key2" : [2,4],
"key3" : [1,2,4],
"key4" : [2,4],
}

new_dict = {}

for k, v in orig.iteritems():
new_dict.setdefault(tuple(v), []).append(k) #need to "freeze" the mutable type into an immutable to allow it to become a dictionnary key (hashable object)

# Here we have new_dict like this :
#new_dict = {
# (2, 4): ['key2', 'key4'],
# (1, 2, 4): ['key3', 'key1']
#}

# like sverre suggested :
final_output = [[k,v] for k,v in new_dict.iteritems()]

关于python - 基于重复值合并字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6184838/

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