python - 基于重复值合并字典

标签 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的方式做到这一点?

最佳答案

您可以像这样反转字典:

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/

相关文章:

python - 向不退出的行添加值

python - 如何矢量化张量中的修改元素

python - numpy 错误 :TypeError: only length-1 arrays can be converted to Python scalars

java - 过滤器列表 : Begin by. .. Android Studio

python - 从字符串列表中删除短重叠字符串

java - 我需要实现一种方法,可以从值中获取键并删除方法

dictionary - Go: map 的类型断言

python - Opencv Python - 来自特征匹配+单应性的相似度分数

java - 链表数组

dictionary - 是否有更好的方式在Dart中编写此数据结构?