Why am I getting duplicate values in my output?
DT
dennistobias at gmail.com
Thu Jul 25 22:44:03 EDT 2019
With the following code:
import csv
class AccessPoint(object):
def __init__(self, name, ipv4, model, location):
self.name = name
self.ipv4 = ipv4
self.model = model
self.location = location
print('{0} born'.format(self.name))
def __del__(self):
print('{0} died'.format(self.name))
def main():
ap_list = []
ap_dict = {}
with open('C:\\inventory.csv', 'r') as csvfile:
csv_reader = csv.DictReader(csvfile)
for row in csv_reader:
ap = AccessPoint(row['Host Name'], row['Static IP Address'], row['Device Model'], row['Host Name'][0:5])
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)
if __name__ == '__main__':
main()
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?
Here is some example output data:
AP1 born
AP2 born
AP1 died
AP3 born
AP2 died
[{'ap_name': 'AP3', 'ap_ipv4': '192.168.1.1', 'ap_model': 'Linksys', 'ap_location': 'HQ'}, {'ap_name': 'AP3', 'ap_ipv4': '192.168.1.1', 'ap_model': 'Linksys', 'ap_location': 'HQ'}, {'ap_name': 'AP3', 'ap_ipv4': '192.168.1.1', 'ap_model': 'Linksys', 'ap_location': 'HQ'}
AP3 died
Thanks in advance.
More information about the Python-list
mailing list