I have made some dictionaries as shown below. When printing the dictionary within the for loop it works and prints all the of the values in the CSV column I want it too.
However, when printing StationList outside of the for loop it only prints the last value of the csv where I want it to print all the values. How would I get the dictionary to output all the values when printing it outside the for loop?
DictConnections = {}
StationList = {}
with open('londonconnections.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile, delimiter = ',')
for row in reader:
Station1 = (row['station1'])
Station2 = (row['station2'])
Time = (row['time'])
DictConnections[Station1, Station2] = Time
StationList = Station1
print(StationList)
Output:
13
Many thanks in advance for any help.
The issue is when you do:
StationList = Station1
the variable StationList
will now point to the current memory position of Station1
.
append()
) all Station1
as you iterate over the rows.For the second possibility you need to create an empty list before the iteration of the rows:
stations = []
then inside the loop (where you had put the print before) you append to the list:
stations.append(Station1)
Now you can print the list:
print(*stations, sep = "\n")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.