将.csv文件加载到字典中并分别打印键和值

时间:2017-12-06 21:08:57

标签: python python-3.x

我在解决如何将多个.csv文件存储到字典中然后分别打印键和值时遇到了麻烦。我必须获取包含不同信息的6个.csv文件并将它们加载到字典中然后编写代码,以便我能够将密钥与其关联的各种值隔离,以便我可以打印ie。 "动物"吃"猎物1,猎物2等#34;

我认为我必须单独执行每个文件,因此6个不同的循环可以为每个键/值列表获取正确的输出,但我尝试的所有内容都给了我一个错误消息。 以下是csv文件和预期输出的示例:

file1.csv:

Rabbit,Grass  
Snake,Mouse  
Mouse,Grass  

输出:

Predator and prey:   
"Rabbit eats grass"    
"Snake eats mouse"  
"Mouse eats grass"  

这是我目前为一个文件编写的代码:

import sys
import csv

inf = open("file1.csv", "r")
reader = csv.reader(inf)

data = {}
for row in reader:
    for i in data.keys():
        print(data[i], "eats", i)

我知道它不对,但我不确定如何在字典中隔离一个.csv文件。我是新编码所以任何帮助将不胜感激! :) 我正在使用 python3 。 谢谢!

2 个答案:

答案 0 :(得分:1)

嗯,你的CSV中没有键(标题字段)或任何东西,只是简单的值对,你只想分别打印每行的元素,这很简单:

import csv

with open("file1.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row[0], "eats", row[1])

哪个应该产生:

Rabbit eats Grass
Snake eats Mouse
Mouse eats Grass

更新:如果要将数据存储到字典中,只需将第一个值用作键,将第二个值用作其中一个值,例如:

import collections
import csv

# we'll use defaultdict to save us some trouble initializing for each predator
predators = collections.defaultdict(set)  # our final dict, use set to filter out duplicates

files = ["file1.csv", "file2.csv", "file3.csv"]  # all of your CSV files

for file in files:  # go through each CSV file...
    with open(file, "r") as f:  # open it...
        reader = csv.reader(f)  # make a CSV reader
        for row in reader:  # go through it line by line
            predators[row[0]].add(row[1])  # add it to the predators dict

for predator in predators:
    print(predator, "eats", predators[predator])

答案 1 :(得分:0)

你应该结帐pandas。 非常适合这种事情。

df = pd.read_csv('file1.csv', names=['Predator','Prey'])
df['statement'] = df.Predator + ' eats ' + df.Prey

for s in df.statement:
    print(s)

如果你想要{'捕食者':'猎物'}你可以做

dic = {pred:prey for pred,prey in df[['Predator','Prey']].values}