In the script below, something strange happens when the second loop starts. The list area_1
changes value even though it is not involved in that loop at all. Same happens with area_2
after the third loop.
server_1 = 'x1'
server_2 = 'x2'
server_3 = 'x3'
table = [
{'Terminal': 'site_1', 'City': 'London', 'Station': server_1},
{'Terminal': 'site_2', 'City': 'London', 'Station': server_1},
{'Terminal': 'site_3', 'City': 'London', 'Station': server_2},
{'Terminal': 'site_4', 'City': 'New York', 'Station': server_3},
{'Terminal': 'site_5', 'City': 'New York', 'Station': server_1},
{'Terminal': 'site_6', 'City': 'New York','Station': server_2},
{'Terminal': 'site_7', 'City': 'Tokyo', 'Station': server_3},
{'Terminal': 'site_8', 'City': 'Tokyo', 'Station': server_3},
{'Terminal': 'site_9', 'City': 'Tokyo', 'Station': server_2}
]
city_index = [
{'City':'London', 'Lat': 51.48,'Long': -0.14 },
{'City':'New York', 'Lat': 40.69,'Long': -74.26 },
{'City':'Tokyo', 'Lat': 35.51,'Long': 138.64 }
]
area_1 = []
for i in city_index:
area_1.append(i)
area_1[-1].update({'Station': server_1, 'Count of terminals': sum(q['City'] == i['City'] and q['Station'] == server_1 for q in table)})
area_2 = []
for i in city_index:
area_2.append(i)
area_2[-1].update({'Station': server_2, 'Count of terminals': sum(q['City'] == i['City'] and q['Station'] == server_2 for q in table)})
area_3 = []
for i in city_index:
area_3.append(i)
area_3[-1].update({'Station': server_3, 'Count of terminals': sum(q['City'] == i['City'] and q['Station'] == server_3 for q in table)})
all = area_1 + area_2 + area_3
for i in all:
print(i)
Output: (Notice the station key)
{'City': 'London', 'Lat': 51.48, 'Long': -0.14, 'Station': 'x3', 'Count of terminals': 0}
{'City': 'New York', 'Lat': 40.69, 'Long': -74.26, 'Station': 'x3', 'Count of terminals': 1}
{'City': 'Tokyo', 'Lat': 35.51, 'Long': 138.64, 'Station': 'x3', 'Count of terminals': 2}
{'City': 'London', 'Lat': 51.48, 'Long': -0.14, 'Station': 'x3', 'Count of terminals': 0}
{'City': 'New York', 'Lat': 40.69, 'Long': -74.26, 'Station': 'x3', 'Count of terminals': 1}
{'City': 'Tokyo', 'Lat': 35.51, 'Long': 138.64, 'Station': 'x3', 'Count of terminals': 2}
{'City': 'London', 'Lat': 51.48, 'Long': -0.14, 'Station': 'x3', 'Count of terminals': 0}
{'City': 'New York', 'Lat': 40.69, 'Long': -74.26, 'Station': 'x3', 'Count of terminals': 1}
{'City': 'Tokyo', 'Lat': 35.51, 'Long': 138.64, 'Station': 'x3', 'Count of terminals': 2}
All 3 lists become identical at the end = area_3
.
Can someone please explain why this is happening? Why are area_1
and area_2
being overwritten?