Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a generator which yields a new dictionary whenever called. Although despite the generator producing a new dictionary the list keeps appending the same dictionary over and over again. My code is like follows.

Python
def dictionary_generator():
    dictionary = {}
    # I create a dictionary.
    ... 
    yield dictionary 

def my_function(var):
    my_list = []
    for i in range(var):
        my_list.append(next(dictionary_generator))
    return my_list

My generator yields the following dictionary for example,
Python
{
'name': 'john',
'age': 26,
'work':'politician'
}
{
'name': 'tom',
'age': 34,
'work':'cricketer'
}
{
'name': 'jimmy',
'age': 99,
'work':'actor'
}

Although my list will look something like this
Python
[
{
'name': 'jimmy',
'age': 99,
'work':'actor'
},
{
'name': 'jimmy',
'age': 99,
'work':'actor'
},
{
'name': 'jimmy',
'age': 99,
'work':'actor'
}
]


Note:
The code is simplified and narrowed to the lines of code where the bug exists

What I have tried:

I have tried different methods of appending the list but all worked as the same way as I described
Posted
Updated 19-Apr-21 8:35am

1 solution

Because your generator function doesn't loop: it always starts at the beginning each time you call it.

See here: How to Use Generators and yield in Python – Real Python[^]
 
Share this answer
 
Comments
CPallini 20-Apr-21 1:57am    
5.
Shubhkarman Singh Sandhu 21-Apr-21 4:35am    
So how can I solve the problem
OriginalGriff 21-Apr-21 4:59am    
Follow the link, read what it says, and think about it.
Me rewt=riting you code to work properly doesn't teach you anything about why my code works and yours doesn't - "yield" is a complicated subject, and you need to understand it, not just parrot an answer that works in one specific case!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900