当列和行已知时,DictReader将获得一个值

2024-05-29 06:18:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了一个csv文件,看起来像这样

ID, name, age, city
1, Andy, 25, Ann Arbor
2, Bella, 40, Los Angeles
3, Cathy, 13, Eureka
...
...

如果我想得到ID=3的city,这在这个例子中是Eureka。有没有一种方法可以有效地做到这一点,而不是迭代每一行?我的php代码每次都会执行这个python脚本来获取值,我觉得每次循环csv文件效率很低。在


Tags: 文件csvnameidcityage例子andy
3条回答

迭代该文件一次并将数据保存到字典中:

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}$

一句话:不

正如yurib所提到的,一种方法是将文件转换成JSON并从那里转移,或者直接转储到dict。如果您需要序列化您的数据集,这使您能够执行诸如pickle之类的操作,或者如果您想将其保存到某个地方供以后使用,shelve。在

另一个选择是使用Python内置的sqlite3支持,将CSV转储到可查询数据库中。这取决于您希望您的开销在哪里:以这种方式预处理数据可以避免每次脚本运行时都要解析一个大文件。在

请查看this answer以快速了解。在

相关问题 更多 >

    热门问题