python - 如何使用键 :value format from a CSV file using Python? 创建字典列表

标签 python csv dictionary

enter image description here

希望列标题作为不带任何引号的键,并将列中的后续值作为键的值。

这是我目前所拥有的:

import csv

with open('zinc3.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print row
        print ("#1\n")

最佳答案

您可以使用 python 中的 pandas 库,它可以处理:

这是一个通用的可重现示例(您需要安装 pandas)

from StringIO import StringIO 
import pandas as pd 

data = """
col1|col2
1|2
21|2
14|2
12|42
10|2
1|27
""" 

# StringIO(data) to simulate a csv file 
# replace it with the name of your csv file 
df = pd.read_csv(StringIO(data), sep="|")

print(df.to_dict(orient="records"))

输出看起来像这样:

[{'col2': 2, 'col1': 1}, {'col2': 2, 'col1': 21}, {'col2': 2, 'col1': 14}, {'col2': 42, 'col1': 12}, {'col2': 2, 'col1': 10}, {'col2': 27, 'col1': 1}]

针对您的具体情况,您需要执行以下操作

import pandas as pd 
df = pd.read_csv("zinc3.csv", sep="|")    
print(df.to_dict(orient="records"))

关于python - 如何使用键 :value format from a CSV file using Python? 创建字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45805821/

相关文章:

python - Tkinter,调用 "wm_iconbitmap"和 "resizable"后闪烁窗口

php - 使用 mysqldump 将表数据导出到 csv 文件

python - 如何在 python 列表中查找彼此相邻的重复项并根据它们的索引列出它们?

c# - 字典键不能用作 Tuple<int[], int> 类型

json - 在 Go 中将 JSON 解码为 map

java - map 的通用 autovivify 函数

python TUI 弹出窗口

python - 如何更新 Celery Task ETA?

python - 根据 Pandas 中的行值划分列

Java从csv读取并显示在jTable上