python - 如何循环遍历字典以更新并返回它?
问题描述
在此代码中,字典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
解决方案
您可以只更新字典中每个键的每个列表:
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)
推荐阅读
- oracle - 如何以表格形式进入下一个字段?
- r - 试图让随机森林运行文本分类
- mongodb - 查询 mongoDB 中的嵌入文档
- asp.net-core - 实例化 DBContext 并从类型(另一个项目)中获取其元数据
- python-3.x - python/pandas 在给定条件的情况下将值写入前一行
- rest - 使用 API 数据更新 Google 表格
- php - 用 OpenCart CMS 的 OpenSSL 加密替换 Mcrypt 加密
- xml - Google表格中的Importxml部分工作
- php - 如何从 $_POST var 类似于用户名的数据库中检索电子邮件
- c# - ViewBag 是否有 OrderBy 选项