python删除列表元素并返回,Python:如何从字典中删除元素并将其作为列表返回?...

I have been trying an exercise that requires me to remove words in a dictionary containing words that are 7 or fewer characters long. So far I have tried using the .values() method to get only the words within the square brackets, and thus create a list to store these words. However, I am having a problem with using the pop method where I get

"TypeError: 'str' object cannot be interpreted as an integer".

Here is my code :

word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],

'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack']}

def main():

edited_synonyms = remove_word(word_dict)

print(edited_synonyms)

def remove_word(word_dict):

synonyms_list = word_dict.values()

new_list = []

for i in synonyms_list:

new_list.extend(i)

for word in new_list:

letter_length = len(word)

if letter_length <= 7:

new_list.pop(word)

return new_list

main()

解决方案

Your program is right. Any ways you need to add index value in pop.

Modified code:

>>> def remove_word(word_dict):

synonyms_list = word_dict.values()

new_list = []

for i in synonyms_list:

new_list.extend(i)

for word in new_list:

letter_length = len(word)

if letter_length <= 7:

new_list.pop(new_list.index(word)) # Modified line

return new_list

Output:

>>> main()

['exhibit', 'communicate', 'manifest', 'disclose', 'unhurried', 'leisurely', 'behind', 'slack']