我有一本这样的字典

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

我想要的是这样的东西。
[
  [
     ["key1", "key3"],
     [1,2,4],
  ],
  [
     ["key2", "key4"],
     [2,4],
  ],
  .....
]

基于唯一值对的键和值的列表。我怎么能用蟒蛇的方式做这个?

最佳答案

你可以这样颠倒措辞:

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/

10-12 21:38