Python 基于重复值合并字典
我有一本这样的词典Python 基于重复值合并字典,python,list,dictionary,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], ], ..... ] 基于唯一值对的键和值列表。我怎样才能以py
{
"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()]
以下是一份清单,说明如何干净利落地完成工作:
[[[key for key in dictionary.keys() if dictionary[key] == value], value]
for value in unique(list(dictionary.values()))]
其中,
unique
可以是返回列表中唯一元素的函数。没有默认设置,但有许多实现()。如果我的示例代码仍然适用于您,请在下面查找:
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)
请注意,要从这里获得指定的结构OP,只需在new_dict.iteritems()中为k,v指定
[[k,v]propoistions@sverre实际上,要获得OP要求的内容,您需要稍微不同:[[k,list(v)]在new_dict.iteritems()中为v,k设置,即切换k和v。另外,Python 3中不存在iteritems()
,如果希望代码段在这两种情况下都能工作,请使用items()。