Title: How to handle the overlaps and remove the words that are substring of any word present?
Tags: python;python-3.x;dictionary
Question: {' Computer': 505,
' Computer Science ': 505,
' Science ': 514,
' Systems ': 977,
' Maths ': 1064,
' Electronics ': 1097}
Here The output should be
' Computer Science ': 505,
' Systems ': 977,
' Maths ': 1064,
' Electronics ': 1097
Comment: can you clarify why the `Output` dict. choose `Computer Science` and not `Computer` or `Science`?   And please show us where do you get stuck - the `minimum code`?


Here is another answer: mydict = {
' Computer': 505,
' Computer Science ': 505,
' Science ': 514,
' Systems ': 977,
' Maths ': 1064,
' Electronics ': 1097
keys_list = list(mydict.keys())
new_dict = {}
for key in keys_list:
new_dict[key] = 0
for key in keys_list:
for key_bis in keys_list:
if key_bis in key and key != key_bis:
new_dict[key_bis] = -1
print (new_dict)
for key in keys_list:
if new_dict[key] < 0:
del new_dict[key]
else:
new_dict[key] = mydict[key]
print (new_dict)
The intermediary labelling:
{' Computer': -1, ' Computer Science ': 0, ' Science ': -1, ' Systems ': 0, ' Maths ': 0, ' Electronics ': 0}
Output:
{' Computer Science ': 505, ' Systems ': 977, ' Maths ': 1064, ' Electronics ': 1097}
Certainly not the most elegant but working as you expect.
Basically you set a negative value to all key strings contained in others. So Computer Science is not contained in Computer or Science whereas Science and Computer are contained in Computer Sciences.
So like that you label the key you don't want, you remove them, and you take back the value from your original dict.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:12/24/20', 'FavoriteCount': 0.0, 'PostTypeId': 1, 'Tags': '<python><python-3.x><dictionary>', 'Title': 'How to handle the overlaps and remove the words that are substring of any word present?', 'ViewCount': 48, 'id': 65434827, 'user_AboutMe': '', 'user_AccountId': 20289986.0, 'user_DisplayName': 'Bitsentinal', 'user_Reputation': 19.0, 'user_Views': 9.0, 'user_id': 14881845.0}}