python - 从dict中删除值

时间:2017-10-16 08:41:08

标签: python

我想创建一个名为remove_short_synonyms()的函数,它传递一个dict 作为参数。参数dict的键是单词和 对应的值是同义词列表。该功能删除所有 每个对应列表少于7个字符的同义词 同义词。

如果这是dict:

synonyms_dict = {'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']}

如何将此作为输出?

{beautiful : ['dazzling', 'handsome', 'magnificent', 'splendid']}

5 个答案:

答案 0 :(得分:2)

利用字典理解和列表理解。

synonyms_dict = {'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']}
synonyms_dict = {k:[v1 for v1 in v if len(v1) >= 7] for k, v in synonyms_dict.items()}
print(synonyms_dict)

# {'beautiful': ['handsome', 'dazzling', 'splendid', 'magnificent']}

​

答案 1 :(得分:2)

我认为您的问题更适合标题为从列表中移除值而不是 dict

您可以使用remove,del或pop删除python列表中的元素。 Difference between del, remove and pop on lists

或者以更加pythonic的方式,我认为,

dict['beautiful'] = [item for item in dict['beautiful'] if len(item)>=7]

答案 2 :(得分:0)

假设您有while (true) { ... switch(...) { .... case "Stop": System.out.println("bye bye"); System.exit(0); break; } } ,初学者的解决方案更易读:

python>=3.x

答案 3 :(得分:0)

这是一个修改现有字典而不是替换现有字典的函数。如果您对同一个字典有多个引用,这将非常有用。

synonyms_dict = {
    'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']
}

def remove_short_synonyms(d, minlen=7):
    for k, v in d.items():
        d[k] = [word for word in v if len(word) >= minlen]

remove_short_synonyms(synonyms_dict)
print(synonyms_dict)

<强>输出

{'beautiful': ['handsome', 'dazzling', 'splendid', 'magnificent']}

请注意,此代码 用新列表替换字典中的现有列表。您可以保留旧的列表对象,如果您确实需要这样做,可以将分配行更改为

d[k][:] = [word for word in v if len(word) >= minlen]

虽然稍微较慢,但可能没有理由这样做。

答案 4 :(得分:0)

def remove_short_synonyms(self, **kwargs):

dict = {}
  word_list = []

  for key, value in synonyms_dict.items():
    for v in value:
      if len(v) > 7:
        word_list.append(v)
    dict[key] = word_list

  print dict


remove_short_synonyms(synonyms_dict)