Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 我是python新手,我想使用python将.csv文件的前两列数据导入字典_Python 2.7_File_Dictionary_Python Import - Fatal编程技术网

Python 2.7 我是python新手,我想使用python将.csv文件的前两列数据导入字典

Python 2.7 我是python新手,我想使用python将.csv文件的前两列数据导入字典,python-2.7,file,dictionary,python-import,Python 2.7,File,Dictionary,Python Import,导入csv mydict = {} with open('factbook.csv', mode='r') as infile: reader = csv.reader(infile) for rows in reader: if rows <=2: mydict.append(reader) print(mydict) mydict={} 打开('factbook.csv',mode='r')作为填

导入csv

 mydict = {}  
 with open('factbook.csv', mode='r') as infile:
     reader = csv.reader(infile)
     for rows in reader:
        if rows <=2:
           mydict.append(reader)
           print(mydict)
mydict={}
打开('factbook.csv',mode='r')作为填充:
reader=csv.reader(infle)
对于读卡器中的行:
如果行后的行

          reader=csv.reader(infile)
加上

          fields = reader.next()
          for row in reader:
              mydict[row[0]]=row[1]

这应该可以。

据我所知,您正试图制作一本字典,将国家名称作为键,将地区作为值。 下面是代码:

import csv

mydict = {}  
with open('factbook.csv', mode='r') as infile:
    reader = csv.reader(infile, delimiter = ',')
    header = reader.next()
    for rows in reader:
        if len(rows) <= 2:
            mydict[rows[0]] = rows[1] # This adds/overwrites keys in a dictionary

print(mydict)

你能更清楚地说明你想要实现什么吗?你想做一个字典列表还是列表的分类?另一方面,您考虑过使用熊猫数据帧吗?不,我不知道熊猫。。我需要存储它们以访问它们的值,这就是我需要的。任何更好的方法都会更好。您可以添加所需词典的结构吗?factbook.csv国家区域(sqkm)阿富汗647500 Akrotiri 123阿尔巴尼亚28748阿尔及利亚2381740美属萨摩亚199one数据位于anothermydict[行[0]=行[1]下方索引器:列表索引超出范围。。。在循环(for循环)中,只需在mydict[row[0]]=row[1]行之前打印len(row),并检查它是否为2。mydict[rows[0]]=rows[1]索引器:列出索引超出范围,但您的答案正是我想要的。。如何解决此错误?对于您在问题中提供的数据集,此方法有效。您的文件有不同的值吗?不,这是一个仅用于5行的结构化数据。。但我有256行和40列数据。。。值是相同的“数据集中的分隔符是什么?”?你的问题中有空格。它们是空格还是逗号?此外,请尝试打印从csv读取的
,以查找问题。
{'Afghanistan': '647500', 'AmericanSamoa': '199', 'Akrotiri': '123', 'Albania': '28748', 'Algeria': '2381740'}