我有一个这样设置的字典
{
"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/