Skip to content

Instantly share code, notes, and snippets.

@meysampg
Created September 11, 2019 15:42
Show Gist options
  • Save meysampg/4da378af3b650c85575cf63a50db4418 to your computer and use it in GitHub Desktop.
Save meysampg/4da378af3b650c85575cf63a50db4418 to your computer and use it in GitHub Desktop.
remove similar key from a dictionary and put the longest key as the final key
def removeSimilarKeyFromDictionary(d, key):
for s in d.keys():
if key.find(s) != -1:
# True with a non-empty list mean the given key is the final key, but it has a candidate on list
return True, s
elif s.find(key) != -1:
# False with a non-empty list mean the iterator key is the final key and its value should sum with
# the value of returned key
return False, s
# False with an empty list mean the given key has no candidate on the list
return False, None
@meysampg
Copy link
Author

result = {'name': 5, 'name ab': 6, 'name a': 3, 'bilim': 5, ' name ': 11}

finalResult = {}
for r in result.keys():
    if len(r) < 3:
        continue
    
    # do some correction on dictionary keys
    newKey = r.replace("ي", "ی") \
                .replace("ك", "ک") \
                .replace("_", " ") \
                .strip()
    
    isOnDic, finalKey = removeSimilarKeyFromDictionary(finalResult, newKey)
    if isOnDic:
        finalResult[newKey] = finalResult[finalKey] + result[r]
        del(finalResult[finalKey])
    else:
        if finalKey is None:
            finalResult.update({newKey: result[r]})
        else:
            finalResult[finalKey] += result[r]


print(result)
print(finalResult)

# {'name': 5, 'name ab': 6, 'name a': 3, 'bilim': 5, ' name ': 11}
# {'name ab': 25, 'bilim': 5}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment