简体   繁体   中英

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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM