Why am I getting duplicate values in my output?

Richard Damon Richard at Damon-Family.org
Fri Jul 26 17:56:05 EDT 2019


On 7/26/19 5:19 PM, DT wrote:
> 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.

dictionaries are mutable.

appending the dictionary to the list adds a reference to that dictionary
to the list, if you change the dictionary latter on, the list is still
refering to that now changed dictionary.

Either you need to copy the dictionary, and add the new copy, or create
a new copy with each iteration of the loop.

At the end of the loop, ap_list is a list of all the same dictionary,
the same one that ap_dict is bound to, you just kept changing it every
time through the loop.

if ap_dict was set to a new empty dictionary in the loop, then all the
copies would be distinct.

-- 
Richard Damon




More information about the Python-list mailing list