Python:如何从字典中删除元素并将其作为列表返回? [英] Python: How do I remove elements from a dictionary and return it as a list?

查看:213
本文介绍了Python:如何从字典中删除元素并将其作为列表返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试一项练习,要求我删除词典中包含7个字符或更少字符的单词.到目前为止,我已经尝试使用.values()方法仅获取方括号内的单词,从而创建一个列表来存储这些单词.但是,我在使用

I have been trying an exercise that requires me to remove words in a dictionary containing words that are 7 or fewer characters long. So far I have tried using the .values() method to get only the words within the square brackets, and thus create a list to store these words. However, I am having a problem with using the pop method where I get

"TypeError:'str'对象无法解释为整数".

"TypeError: 'str' object cannot be interpreted as an integer".

这是我的代码:

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

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    synonyms_list = word_dict.values()
    new_list = []
    for i in synonyms_list:
        new_list.extend(i)

    for word in new_list:
        letter_length = len(word)
        if letter_length <= 7:
            new_list.pop(word)

    return new_list

main()

推荐答案

您的程序正确.您需要在pop中添加index值的任何方式.

Your program is right. Any ways you need to add index value in pop.

修改后的代码:

>>> def remove_word(word_dict):
    synonyms_list = word_dict.values()
    new_list = []
    for i in synonyms_list:
        new_list.extend(i)

    for word in new_list:
        letter_length = len(word)
        if letter_length <= 7:
            new_list.pop(new_list.index(word)) # Modified line

    return new_list


输出:

>>> main()
['exhibit', 'communicate', 'manifest', 'disclose', 'unhurried', 'leisurely', 'behind', 'slack']

这篇关于Python:如何从字典中删除元素并将其作为列表返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆