-2

I am facing a problem where I have to merger different elements of a dictionary based on some condition. What is the most pythonic way to achieve that?

For example , I have the below dictionary

dict = {
    'a': [element1 , element2]
    'b': [element2, element3]
    'c': [element4, element5, element1]
    'd': []
}

My resulting dictionary should be

dict = {
 'a': [element1, element2, element3, element4, element5]
}

What would be the best way to achieve that?

I want to merge them based upon condition which is evaluated by is_compatible method. So lets' say I will merge two elements if this function returns true Is there a way I can do this?

Deepanshu Arora
  • 375
  • 1
  • 5
  • 21

2 Answers2

4
result = {
    'a': list(set().union(*input_dict.values()))
}
Marat
  • 15,215
  • 2
  • 39
  • 48
0

I don't clearly get what you want to do, but it seems like you want to combine all lists as a set. You can do something like this:

new_list = []
for element in dict.values():
    for value in element:
        new_list.append(element)
new_list = list(set(new_list))
new_dict = {
    dict.keys[0]: new_list
}

Hope this helps!

Krishnan Shankar
  • 780
  • 9
  • 29