繁体   English   中英

在python中用CSV文件创建字典

[英]Creating a dictionary out of a CSV file in python

我有一个带有邮政编码及其时区的CSV文件。 如何将CSV文件转换为字典? 这将是一个更大的任务模块。 我的代码看起来像这样,我仍然坚持下一步做什么:

import csv

with open('zipcode.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row

input_file = csv.DictReader(open("zipcode.csv"))

猜测你的文件结构,试试这个:

import csv

my_dict = {}

with open('zipcode.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        my_dict[row[0]] = row[1]

我不确定你的数据文件是什么样的,但是这里有一种使用pandas DataFrame的方法,假设你的csv文件有两列:zip_code和time_zone,用逗号分隔,没有任何标题:

import pandas as pd
df = pd.read_csv('zipdata.csv', header=None) 
my_dict = dict(zip(df[0], df[1]))

这个简单的脚本应该可以帮助您解决问题。 您不需要使用DictReader

test.py

import csv

# Open the file
with open('zipdata.csv') as f:
  # Populate a dictionary with the reader
  my_dict = dict(csv.reader(f))

# Print the key-value pairs
for k, v in my_dict.iteritems():
  print("{}: {}".format(k, v))

我使用自己的测试csv文件, test.csv ,这是输出:

23:59 $ cat test.csv
hello, world
test, testing
✔ ~ 
23:59 $ python test.py 
test:  testing
hello:  world

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM