Why am I getting duplicate values in my output?

DT dennistobias at gmail.com
Fri Jul 26 17:19:12 EDT 2019


On Thursday, July 25, 2019 at 9:57:38 PM UTC-5, Chris Angelico wrote:
> On Fri, Jul 26, 2019 at 12:46 PM DT <dennistobias at gmail.com> wrote:
> > def main():
> >     ap_list = []
> >     ap_dict = {}
> >
> >         for row in csv_reader:
> >             ap_dict['ap_name'] = ap.name
> >             ap_dict['ap_ipv4'] = ap.ipv4
> >             ap_dict['ap_model'] = ap.model
> >             ap_dict['ap_location'] = ap.location
> >
> >             ap_list.append(ap_dict)
> >
> >         print(ap_list)
> >
> >
> > When I execute print(ap_list) I get the very last row in the CSV repeated once for every row in the file. I would expect to see a list of ap_dicts, but I do not. When I add print(ap_dict) directly after the ap_list.append(ap_dict) inside the loop I see the correct values. Why is it that the print(ap_list) that happens outside of the for loop is only printing the last item on repeat?
> >
> 
> You create one dictionary, and then reuse it every time. Appending it
> to a list doesn't change it, which means you keep overwriting the same
> dictionary every time you go through the loop.
> 
> Try creating a new dictionary for each row; in fact, you can simplify
> things significantly by using a dict literal (or, more technically,
> "dict display") to create a new dictionary with the four fields
> already set. You could even do that in the same operation as appending
> to the list.
> 
> ChrisA

That is interesting to know. I guess I was confused because when I put in a print(ap_dict) in the for loop, it printed out the contents of the dict correctly for each pass. I assumed that when I then added that dict into the list that the list would be appended with that iterations values. I guess I have a bit to learn about how things are referenced in Python.

Thanks for the hint. I updated my code and it works correctly now.



More information about the Python-list mailing list