I am writing a for loop that will go through the values in my_dictionary as well as the values in the list. If a word from the list "words" is in the my_dictionary then append the list of values where the word was found once. The code below ran the code but the list look larger than I expected.
my_dictionary = {1: ['apple','dog','cat','bird'],
2: ['mouse','rat','elephant','donkey'],
3: ['tiger','lion','bear','tortoise']}
words = ['apple', 'dog', 'mouse', 'bear','tortoise']
def cen_lst(my_dict, words):
new_lst = []
for key, value in my_dict.items():
for word in words:
if word in value:
new_lst.append(value)
return new_lst
output I expected:
['apple','dog','cat','bird', 'mouse','rat','elephant','donkey', 'tiger','lion','bear','tortoise' ]
Instead the output I am getting is:
[['apple', 'dog', 'cat', 'bird'],
['apple', 'dog', 'cat', 'bird'],
['mouse', 'rat', 'elephant', 'donkey'],
['tiger', 'lion', 'bear', 'tortoise'],
['tiger', 'lion', 'bear', 'tortoise']]
CodePudding user response:
Every time it found a matching word it appends the entire list because of this line:
new_lst.append(value)
The value for each iteration was the entire list at that key. That's why you got a list of lists. Simply replace value with word. This causes it to just append the matching word, not the list that the word is inside.
new_list.append(word)
CodePudding user response:
According to your description, you should use list.extend
instead of list.append
(you can refer to this for their differences), and do not extend every time the retrieval is successful:
>>> def cen_lst(my_dict, words):
... new_lst = []
... for value in my_dict.values():
... if any(word in value for word in words):
... new_lst.extend(value)
... return new_lst
...
>>> cen_lst(my_dictionary, words)
['apple',
'dog',
'cat',
'bird',
'mouse',
'rat',
'elephant',
'donkey',
'tiger',
'lion',
'bear',
'tortoise']