根据重复值合并字典

use*_*291 2 python dictionary list

我有一个这样的字典设置

{
     "key1" : [1,2,4],
     "key2" : [2,4],
     "key3" : [1,2,4],
     "key4" : [2,4],
     ....
}
Run Code Online (Sandbox Code Playgroud)

我想要的是这样的.

[
  [ 
     ["key1", "key3"],
     [1,2,4],
  ],
  [ 
     ["key2", "key4"],
     [2,4],
  ],
  .....
]
Run Code Online (Sandbox Code Playgroud)

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

Céd*_*ien 5

您可以像这样反转字典:

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()]
Run Code Online (Sandbox Code Playgroud)