[英]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.
在 for 循环中打印字典时,它可以工作并打印 CSV 列中的所有值,我也想要它。
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.但是,当在 for 循环之外打印 StationList 时,它只打印 csv 的最后一个值,我希望它打印所有值。 How would I get the dictionary to output all the values when printing it outside the for loop?
在 for 循环外打印时,如何将字典获取到 output 的所有值?
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
.变量
StationList
现在将指向Station1
的当前 memory position 。
append()
) all Station1
as you iterate over the rows.append()
)所有Station1
。 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:然后在循环内(之前放置打印的地方)你 append 到列表中:
stations.append(Station1)
Now you can print the list:现在您可以打印列表:
print(*stations, sep = "\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.