通过同一词典中的公用值合并键 [英] Merge Keys by common value from the same dictionary

查看:105
本文介绍了通过同一词典中的公用值合并键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一本包含以下内容的字典:

Let's say that I have a dictionary that contains the following:

myDict = {'A':[1,2], 'B': [4,5], 'C': [1,2]}

我想创建一个新字典,merged通过具有相似的值来合并键,所以我的merged将是:

I want to create a new dictionary, merged that merges keys by having similar values, so my merged would be:

merged ={['A', 'C']:[1:2], 'B':[4,5]} 

我尝试使用此线程中建议的方法,但无法复制我的需求.

I have tried using the method suggested in this thread, but cannot replicate what I need.

有什么建议吗?

推荐答案

您所要求的内容是不可能的.您在假设字典中的键使用可变列表.由于可变数据不能被散列,因此您不能将其用作字典键.

What you have asked for is not possible. Your keys in the hypothetical dictionary use mutable lists. As mutable data can not be hashed, you cant use them as dictionary keys.

编辑,我可以按照您的要求去做,除了其中的键都是元组.这段代码是一团糟,但是您可以清理它.

Edit, I had a go to doing what you asked for except the keys in this are all tuples. This code is a mess but you may be able to clean it up.

myDict = {'A':[1,2],
          'B': [4,5],
          'C': [1,2],
          'D': [1, 2],
          }


myDict2 = {k: tuple(v) for k, v in myDict.items()}
print(myDict2) #turn all vlaues into hasable tuples

#make set of unique keys
unique = {tuple(v) for v in myDict.values()}
print(unique) #{(1, 2), (4, 5)}

"""
iterate over each value and make a temp shared_keys list tracking for which
keys the values are found. Add the new key, vlaue pairs into a new
dictionary"""
new_dict = {}
for value in unique:
    shared_keys = []
    for key in myDict:
        if tuple(myDict[key]) == value:
            shared_keys.append(key)
    new_dict[tuple(shared_keys)] = value
print(new_dict) #{('A', 'C'): (1, 2), ('B',): (4, 5)}

#change the values back into mutable lists from tuples
final_dict = {k: list(v) for k, v in new_dict.items()}
print(final_dict)

这篇关于通过同一词典中的公用值合并键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆