Reputation: 397
I have the following type of dictionaries that I would like to merge on common values. Values are B-Disease, I-Disease etc., where B stands for beginning and I stands for the end.
{'allergen': 'B-Disease'}
{'allergic': 'B-Disease'}
{'symptoms': 'I-Disease'}
{'allergic': 'B-Disease'}
{'symptoms': 'I-Disease'}
{'allergen-specific': 'B-Disease'}
I would like to combined the keys (allergen, allergic, symptoms etc.) in such a way that if the key has a B value then it should be concatenated with the next entity provided that the next entity also have a B value. But if the next value is I then that should be ending key to concatenate. These steps needs to be repeated for all the keys.
The resulting dictionary should look like:
{'Disease': ['allergen allergic symptoms']}
{'Disease': ['allergic symptoms']}
{'Disease': ['allergen-specific']}
or
{'Disease': ['allergen allergic symptoms', 'allergic symptoms', 'allergen-specific']}
Can anyone help in solving this?
Upvotes: 0
Views: 31
Reputation: 571
I assume your dictionaries are stored in a list.
Try this:
dict_list = [{'allergen': 'B-Disease'},{'allergic': 'B-Disease'},{'symptoms': 'I-Disease'},
{'allergic': 'B-Disease'},{'symptoms': 'I-Disease'},{'allergen-specific': 'B-Disease'}]
disease = {'Disease':[]}
output_list = []
for i, d in enumerate(dict_list):
if (list(d.values())[0] == 'I-Disease'):
output_list.append(disease)
disease = {'Disease':[]}
continue
disease['Disease'].append(list(d.keys())[0])
if (i == len(dict_list)-1):
output_list.append(disease)
Output:
print(output_list)
[{'Disease': ['allergen', 'allergic']},
{'Disease': ['allergic']},
{'Disease': ['allergen-specific']}]
Upvotes: 1