【发布时间】:2019-05-25 12:56:27
【问题描述】:
在此代码中,字典 word_dict 中包含 7 个或更少字符的任何值(同义词)都将从字典中删除。
我设法删除了包含 7 个或更少字符的值,最初,我尝试创建一个新字典来存储更新后的值,但没有成功,我弄乱了我的代码。
关于如何在不创建新字典的情况下编辑现有字典值的任何想法?我更喜欢不必使用集合、推导式或单行代码来完成此任务。预期的输出应该是这样的:(可以是任何顺序)
{
'show' : ['communicate', 'manifest', 'disclose'],
'dangerous' : ['hazardous', 'perilous', 'uncertain'],
'slow' : ['leisurely', 'unhurried'],
}
我尝试用来解决问题的代码,主要位于 remove_word(word_dict) 函数中。
word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],
'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}
def main():
edited_synonyms = remove_word(word_dict)
print(edited_synonyms) #should print out an edited dictionary
def remove_word(word_dict):
dictionary = {}
synonyms_list = word_dict.values()
new_list = []
for i in synonyms_list:
new_list.append(i)
for word in new_list:
letter_length = len(word)
if letter_length <= 7:
new_list.pop(new_list.index(word))
return dictionary
【问题讨论】:
-
这是这个问题的延伸吗? stackoverflow.com/questions/56254228/…
标签: python list dictionary for-loop