On Fri, Jul 26, 2019 at 12:46 PM DT <dennistob...@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
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to