根据重复值合并字典

时间:2011-05-31 08:25:33

标签: python list dictionary

我有一个像这样设置的字典

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

我想要的是这样的。

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

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

3 个答案:

答案 0 :(得分: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()]

答案 1 :(得分:1)

这是一份干净利落地完成工作的清单:

[[[key for key in dictionary.keys() if dictionary[key] == value], value]
   for value in unique(list(dictionary.values()))]

其中unique可以是返回列表的唯一元素的函数。这没有默认值,但有很多实现(here are some)。

答案 2 :(得分:0)

如果您的实际代码仍然存在,请查看下面的示例代码:

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

unique = map(list, set(map(tuple, orig.values())))
print map(lambda val: [val, filter(lambda key: orig[key] == val, orig)], unique)