首页 > 解决方案 > 如何循环遍历字典以更新并返回它?

问题描述

在此代码中,字典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

标签: pythonlistdictionaryfor-loop

解决方案


您可以只更新字典中每个键的每个列表:

for key, value in word_dict.items():
    temp = []
    for item in value:
        if len(item) > 7:
            temp.append(item)
    word_dict[key] = temp

编辑:实际上,您不必创建新temp列表,您可以使用删除:

for key, value in word_dict.items():
    for item in value:
        if len(item) > 7:
            value.remove(item)

推荐阅读