【问题标题】:How to create a dictionary from CSV using a loop function?如何使用循环函数从 CSV 创建字典?
【发布时间】:2018-06-18 05:54:51
【问题描述】:

我正在尝试从 CSV 的 cmets 表中创建几个字典,其中包含以下列:

我需要为每一行创建一个字典(希望使用循环,这样我就不必手动创建它们),其中字典键是:

  • 身份证
  • 评论类型
  • 评论

但是,我想不出一个快速的方法来做到这一点。我尝试使用以下代码创建字典列表:

# Import libraries
import csv
import json
import pprint

# Open file
reader = csv.DictReader(open('Comments.csv', 'rU'))

# Create list of dictionaries
dict_list = []
for line in reader:
    dict_list.append(line)

pprint.pprint(dict_list)

但是,现在我不知道如何访问字典或键值对是否正确匹配,如下图所示:

  • ID、ReviewType 和 Comment 似乎没有显示为 字典键
  • Comment 值似乎显示为半句列表。

有没有办法只为每一行创建一个字典而不是一个字典列表?

注意:我确实看过this 问题,但它并没有真正帮助。

【问题讨论】:

  • 按照您指定问题的方式,您似乎期待某种稀疏输入,否则使用列表可能会更好,不是吗?
  • 另外,我看不出字典的(唯一)键是什么。假设您有三个不同的字典,您希望如何访问它们中的每一个?只需通过 ID?
  • 你会得到一个OrderedDict 作为结果。您可以像普通的dict 一样访问它。 (或者您可以从中创建一个dict - 如果您愿意的话。) cmets 很好; pprint 只是将它们放在多行上。
  • 使用字典的目的是因为我想稍后使用 NLTK 显示单词的计数。字典的唯一键是 ID。
  • @drmyrnz 我的解决方案有效吗?

标签: python-3.x csv dictionary


【解决方案1】:

给你。我将评论放入数组中

# Import libraries
import csv
import json
import pprint

# Open file


def readPerfReviewCSVToDict(csvPath):
    reader = csv.DictReader(open(csvPath, 'rU'))

    perfReviewsDictionary = []
    for line in reader:
        perfReviewsDictionary.append(line)

    perfReviewsDictionaryWithCommentsSplit = []
    for item in perfReviewsDictionary:
        itemId = item["id"]
        itemType = item["type"]
        itemComment = item["comments"]
        itemCommentDictionary = []
        itemCommentDictionary = itemComment.split()
        perfReviewsDictionaryWithCommentsSplit.append({'id':itemId, 'type':itemType, 'comments':itemCommentDictionary})

    return perfReviewsDictionaryWithCommentsSplit

dict_list = readPerfReviewCSVToDict("test.csv")
pprint.pprint(dict_list)

输出是:

[{'comments': ['test', 'ape', 'dog'], 'id': '1', 'type': 'Test'},
 {'comments': ['dog'], 'id': '2', 'type': 'Test'}]

【讨论】:

  • 没问题 - 很高兴为您提供帮助
【解决方案2】:

由于您没有给出可重现的示例,因此我为您创建了一个示例 DataFrame

import pandas as pd
df = pd.DataFrame([[1, "Contractor", "Please post"], [2, "Developer", "a reproducible example"]])
df.columns = ['ID', 'ReviewType', 'Comment']

在您的计算机中,输入:

df = pd.read_csv(file_path)

将 csv 文件作为 pandas DataFrame 读取。

现在我将创建一个名为 dictList 的列表,该列表最初为空,我将为 DataFrame df 中的每一行填充一个字典

dictList = []

#Iterate over each row in df
for i in df.index:

    #Creating an empty dictionary for each row
    rowDict = {}

    #Populating it
    rowDict['ID'] = df.at[i, 'ID']
    rowDict['ReviewType'] = df.at[i, 'ReviewType']
    rowDict['Comment'] = df.at[i, 'Comment']

    #Once I'm done populating it, I will append it to the list
    dictList.append(rowDict)

    #Go to the next row and repeat.

现在遍历我们为我的示例创建的字典列表

for i in dictList:
    print(i)

我们得到

{'ID': 1, 'ReviewType': 'Contractor', 'Comment': 'Please post'}
{'ID': 2, 'ReviewType': 'Developer', 'Comment': 'a reproducible example'}

【讨论】:

  • 这很有帮助,谢谢。我真的很喜欢你也解释了一切,但是我尽量避免使用列表。
【解决方案3】:

你想要这个吗?

DICT = {}
for line in reader:
    DICT[line['ID']] = line

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 2020-06-20
    相关资源
    最近更新 更多