I am sorry if this is too easy but I can't figure out how to build this dictionary.
I have a string for example
"Bob and Anna are meeting at noon"
and I want a dictionary with all palindromes pointing to a list of the following not-palindromes, so
{"Bob": ["and"], "Anna": ["are", "meeting", "at"], "noon": []}
I found out that I can check if a word is a palindrome with
word.lower() == word.lower()[::-1]
and I can also split a string into words with
string.split()
but I don't understand how to loop over the string and build the dictionary so that only the palindromes are keys and make a list at the same time.
Thanks for any help
This code should work:
text = "Bob and Anna are meeting at noon"
words = {}
last_p = None
for word in text.split():
word2 = word.lower()
if word2 == word2[::-1]:
words[word] = []
last_p = word
elif last_p:
words[last_p].append(word)
print(words)
If there are any words in the sentence before the first palindrome, they will be ignored. If you want the items in the dictionary to stay in their original order, use the collections.OrderedDict
class instead of the builtin dict
.