迭代通过dict只使用3行

时间:2017-05-22 19:16:28

标签: python python-3.x

我有一个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/

1 个答案:

答案 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...