简体   繁体   中英

Python: Printing dictionary outside of for loop only prints last value

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 .

So to resolve the "issue" two possibilities:

  1. Put back the print inside the loop.
  2. Create a list and add ( 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM