我有一个csv文件,我导入到dict中。 有没有办法迭代字典,只抓取链接并将它们传递到列表迭代到bs4?
with open('/Users/paribaker/Google Drive/Paxwin/Data/cits.csv') as f:
reader = csv.DictReader(f)
for row in reader:
for k, v in row.items():
print(k, v)
结果是:
id 166
city NO Norway
link http://www.fallingrain.com/world/NO/
id 167
city NP Nepal
link http://www.fallingrain.com/world/NP/
id 168
city NR Nauru
link http://www.fallingrain.com/world/NR/
id 169
city NS Suriname
link http://www.fallingrain.com/world/NS/
id 170
city NU Nicaragua
link http://www.fallingrain.com/world/NU/
答案 0 :(得分:3)
根据您的输出:
with open("/Users/paribaker/Google Drive/Paxwin/Data/cits.csv") as f:
reader = csv.DictReader(f)
links = [row["link"] for row in reader]
print(links) # or do whatever you want with the list...
修改强>:
如果输入CSV很大(如数百万行),您可能需要查找link
列的位置并将行读作列表,而不是将每行转换为dict
。类似的东西:
with open("/Users/paribaker/Google Drive/Paxwin/Data/cits.csv") as f:
reader = csv.reader(f)
index = next(reader).index("link")
links = [row[index] for row in reader]
print(links) # or do whatever you want with the list...