Home > Mobile >  How to delete dictionary key-value pairs if a substring is found at the end of more than one key?
How to delete dictionary key-value pairs if a substring is found at the end of more than one key?

Time:03-01

Suppose I have the following dictionary:

dictionary = {
'thegreenmile': '1999',
'scarface': '1983',
'fightclub': '1999',
'thebluemile': '1776',
'theyellowmile': '1893'
}

I want Python to look through the dictionary. If there are keys that end in identical ways, remove the key-value pairs. In the dictionary above, that means while the key-value pair associated with the key thegreenmile remains, the other two key-value pairs associated with the keys thebluemile and theyellowmile are deleted.

You might ask, "What about the beginning? I see the word the duplicated." I'm only focusing on the end, and I haven't been successful in finding something that would allow me to target only the end (I do know about .strip(), but that's very different.)

How can I make it so that Python keeps only one key-value pair if it happens that multiple keys share the same ending? I'm thinking of a threshold of four identical characters at the end.

CodePudding user response:

You might try it this way, if you want to keep multiple values with the same suffix, try saving them in the same list, or in a format like json

dictionary = {'thegreenmile': '1999', 'scarface': '1983', 'fightclub': '1999', 'thebluemile': '1776', 'theyellowmile': '1893'}

keys, new_dic = set(), {}
for k, v in dictionary.items():
    if k[-4:] not in keys:
        keys.add(k[-4:])
        new_dic[k] = v
print(new_dic)
  • Related