Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return a dictionary with only palindromes of key + value

How to return a dictionary with only palindromes of key + value.(assignment)

def isPalindrome(dict1):
   newDict = dict1.copy().items()
   for key,value in newDict:
      result = key + value
      for index in range(len(result)):
         if result[index] != result[len(result) - 1 - index]:
            del dict1[key]
   return dict1
   
dictionary = {
   "kaj":"ak",
   "ado":"lescent",
   "gu":"ug"
}
print(isPalindrome(dictionary))

Current Output:

File "dict.py", line 7, in isPalindrome
    del dict1[key]
KeyError: 'ado' 

Desired Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'kaj': 'ak','gu': 'ug'} 

>Solution :

After deleting the key from the dictionary, the loop keeps on running and may try to delete it a second time, which raises the KeyError you are seeing.

Use a break statement after the del to stop as soon as the entry is deleted.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading