Skip to content Skip to sidebar Skip to footer

Merge Keys By Common Value From The Same Dictionary

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 s

Solution 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:
        iftuple(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)

Post a Comment for "Merge Keys By Common Value From The Same Dictionary"