Python: How do I remove elements from a dictionary

2020-07-26 02:29发布

问题:

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' object cannot be interpreted as an integer".

Here is my code :

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()

回答1:

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

Modified code:

>>> 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

Output:

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


回答2:

Try this :

outp = {k: [v for v in word_dict[k] if len(v)<=7 ]for k in word_dict}

Output :

{'show': ['communicate', 'manifest', 'disclose'], 'slow': ['unhurried', 'leisurely']}


回答3:

On a list you can pop elements based on the index.

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 = list()
    for i in synonyms_list:
        new_list.extend([word for word in i if len(word) > 7])
    return new_list

main()


回答4:

Personally I would do it like this:

for key in word_dict.keys():
    word_dict[key] = [x for x in word_dict[key] if len(x)>7]


回答5:

Or you can use the remove property of list in the below way:-

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

Alternate way:-

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


回答6:

You should use remove function instead of pop

The remove() function takes a single element as an argument.

The pop() function takes a single argument (index) and removes the item present at that index.

More details :

https://docs.python.org/3/tutorial/datastructures.html



回答7:

list.pop takes as an argument the index of the item you want to pop from the list, but when you do new_list.pop(word), you are actually providing the item itself, hence the error.

From the docs: https://docs.python.org/3/tutorial/datastructures.html

list.pop([i])
Remove the item at the given position in the list, and return it. You can easily solve this using dictionary comprehension, where you only include values in your list, with length > 7

To fix this, just find the index of the word you want to pop via list.remove()

So the line

 new_list.pop(word)

will change to

 new_list.remove(word)

But a better approach might be to use a list comprehension like so

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

#Iterate through the values of the list and pick one with length > 7
res = [v for value in word_dict.values() for v in value if len(v) > 7  ]
print(res)

The output will be

['communicate', 'manifest', 'disclose', 'unhurried', 'leisurely']


回答8:

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


res =[]

for i in word_dict:
    tmp =[j for j in word_dict[i] if len(j)<=7]
    res.extend(tmp)

print(res)

# output ['display', 'exhibit', 'convey', 'gradual', 'late', 'behind', 'tedious', 'slack']