【问题标题】:How can I loop through a dictionary to update it and return it?如何遍历字典以更新并返回它?
【发布时间】: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

【问题讨论】:

标签: python list dictionary for-loop


【解决方案1】:

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

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)

【讨论】:

  • 谢谢,但我应该早点指定这个,有没有什么方法可以在不删除功能的情况下完成这个?
  • 您的意思是要在代码中保留remove_word 函数吗?如果是,您可以将此代码放在函数体中。请注意,由于字典是可变的,因此您不必返回 word_dict。该函数将修改传递给函数的字典。
  • 是的,但奇怪的是它为我打印了“无”。
  • 是的,如果你使用edited_synonyms = remove_word(word_dict) 那么edited_synonyms 是none,因为函数不返回任何东西。相反,您应该输入:print(word_dict)
  • 如果我这样做,它似乎不会为我更新字典。
【解决方案2】:

您可以像下面这样从现有列表中过滤掉值。


from pprint import pprint

word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],
             'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack'],
             'dangerous': ['perilous', 'hazardous', 'uncertain']}

for k, v in word_dict.items():
    word_dict[k] = list(filter(lambda x: len(x) > 7, v))

pprint(word_dict)


输出:

{'dangerous': ['perilous', 'hazardous', 'uncertain'],
 'show': ['communicate', 'manifest', 'disclose'],
 'slow': ['unhurried', 'leisurely']}

【讨论】:

  • 比其他初学者的解决方案要好得多:) +1
【解决方案3】:

有两种方法可以做到这一点:

  1. 您可以简单地构造一个具有相同变量的字典并使用列表推导填充每个键的值。

    from pprint import pprint
    
    word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],
                 'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack'],
                 'dangerous': ['perilous', 'hazardous', 'uncertain']}
    
    for key_word in word_dict:    # loops through each identifier word
        word_dict[key_word] = [   # list comprehensioin
                word
                for word in word_dict[key_word] # fetch the original words list 
                if len(word) > 7  # fetches the list of words of size gt 7
        ]
    
    pprint(word_dict)
    
  2. 使用纯字典理解

    word_dict = {key_word: [word for word in word_dict[key_word] if len(word) > 7] for key_word in word_dict}
    

这两个结果都是

{'dangerous': ['perilous', 'hazardous', 'uncertain'],
 'show': ['communicate', 'manifest', 'disclose'],
 'slow': ['unhurried', 'leisurely']}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2012-03-09
    • 2014-05-04
    • 1970-01-01
    • 2020-03-05
    • 2015-11-20
    • 1970-01-01
    相关资源
    最近更新 更多