Merge Keys by common value from the same dictionary

心已入冬 提交于 2020-03-06 04:38:12

问题


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

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

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.

Any suggestions?


回答1:


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)


来源:https://stackoverflow.com/questions/44392023/merge-keys-by-common-value-from-the-same-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!