data = {}
with open('input.csv') as fin:
reader = csv.DictReader(fin)
for record in reader:
data[record['ID']] = {k:v for k,v in record.items() if k <> 'ID'}
然后只需在字典中访问所需的密钥:
^{pr2}$
如果您想在键:值格式您可以将其另存为json文件:
import json
import csv
j = {}
with open('input.csv') as fin:
reader = csv.DictReader(fin)
for record in reader:
j[record['ID']] = {k:v for k,v in record.items() if k <> 'ID'}
with open('output.json','w') as fout:
json.dump(j,fout)
If I want to get the city of ID=3, which would be Eureka for this
example. Is there a way to do this efficiently instead of iterating
each row? My php code will be executing this python script each time
to get the value, and I feel like being very inefficient to loop
through the csv file every time.
理想的解决方案是将这个Python代码打包到一个API中,您可以从PHP代码调用它。在
启动时,Python代码会将文件加载到数据结构中,然后等待您的请求。在
如果文件非常大,Python脚本会将其加载到数据库中并从中读取。在
然后可以选择返回字符串或json对象。在
下面是一个使用Flask的示例:
import csv
from flask import Flask, request, abort
with open('somefile.txt') as f:
reader = csv.DictReader(f, delimiter=',')
rows = list(reader)
keys = row[0].keys()
app = Flask(__name__)
@app.route('/<id>')
@app.route('/')
def get_item():
if request.args.get('key') not in keys:
abort(400) # this is an invalid request
key = request.args.get('key')
try:
result = next(i for i in rows if i['id'] == id)
except StopIteration:
# ID passed doesn't exist
abort(400)
return result[key]
if __name__ == '__main__':
app.run()
迭代该文件一次并将数据保存到字典中:
然后只需在字典中访问所需的密钥:
^{pr2}$如果您想在键:值格式您可以将其另存为
json
文件:理想的解决方案是将这个Python代码打包到一个API中,您可以从PHP代码调用它。在
启动时,Python代码会将文件加载到数据结构中,然后等待您的请求。在
如果文件非常大,Python脚本会将其加载到数据库中并从中读取。在
然后可以选择返回字符串或json对象。在
下面是一个使用
Flask
的示例:你可以这样称呼它:
^{pr2}$一句话:不
正如yurib所提到的,一种方法是将文件转换成JSON并从那里转移,或者直接转储到
dict
。如果您需要序列化您的数据集,这使您能够执行诸如pickle
之类的操作,或者如果您想将其保存到某个地方供以后使用,shelve
。在另一个选择是使用Python内置的
sqlite3
支持,将CSV转储到可查询数据库中。这取决于您希望您的开销在哪里:以这种方式预处理数据可以避免每次脚本运行时都要解析一个大文件。在请查看this answer以快速了解。在
相关问题 更多 >
编程相关推荐