背景:
我在尝试搜索某些 CSV 文件时遇到问题。
我已经浏览了 python 文档:http://docs.python.org/2/library/csv.html
关于 csv 模块的 csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
对象。
我的理解是,csv.DictReader
假定文件的第一行/行是字段名称,但是,我的 csv 字典文件只是以“key”、“value”开头,然后继续至少 500,000 行。
我的程序将询问用户他们正在寻找的标题(即键),并使用打印功能将值(即第二列)显示到屏幕上。我的问题是如何使用 csv.dictreader 搜索特定键并打印其值。
示例数据: 下面是 csv 文件及其内容的示例...
"Mamer","285713:13"
"Champhol","461034:2"
"Station Palais","972811:0"
因此,如果我想找到“Station Palais”(输入),我的输出将是 972811:0。我能够操作字符串并创建整个程序,我只需要 csv.dictreader 的帮助。我感谢任何帮助。
编辑部分:
import csv
def main():
with open('anchor_summary2.csv', 'rb') as file_data:
list_of_stuff = []
reader = csv.DictReader(file_data, ("title", "value"))
for i in reader:
list_of_stuff.append(i)
print list_of_stuff
main()
最佳答案
您链接到的文档提供了一半的答案:
class
csv.DictReader
(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)[...] maps the information read into a dict whose keys are given by the optional fieldnames parameter. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames.
看起来,如果传递 fieldnames
参数,则给定文件将不会将其第一条记录解释为 header (将使用该参数)。
# file_data is the text of the file, not the filename
reader = csv.DictReader(file_data, ("title", "value"))
for i in reader:
list_of_stuff.append(i)
这将(显然;我一直遇到麻烦)产生以下数据结构:
[{"title": "Mamer", "value": "285713:13"},
{"title": "Champhol", "value": "461034:2"},
{"title": "Station Palais", "value": "972811:0"}]
可能需要通过如下方式进一步将其转化为标题到值的映射:
data = {}
for i in list_of_stuff:
data[i["title"]] = i["value"]
现在只需使用 data
的键和值即可完成您的任务。
这里是字典理解:
data = {row["title"]: row["value"] for row in csv.DictReader(file_data, ("title", "value"))}
关于csv - 使用Python的csv.dictreader搜索特定键然后打印其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16641461/