首页 > 解决方案 > 从 OrderDict 到字典 python

问题描述

假设由于循环到 csv 文件,我得到以下命令字典:

OrderedDict([('NAME', 'Apple'), ('Colour', 'red'), ('Type', 'Fruit'), ('COMMENT', 'Fuji')])

我的数据框格式的 csv

  NAME                 Colour             Type         COMMENT
 Apple                  red               Fruit        Fuji
 Apple                  green             Fruit        nan

我打开 csv 文件的代码是:

reader =csv.DictReader(csvfile)

record_dictionary = {}

for k,row in reader:
    print(row)
    record_dictionary = {row for row in reader if not row['COMMENT']}

我的 csv 文件有 4 列,我想将每一列作为键值对传递,并且列 COMMENT 不能是 nan。所以我在这种情况下的最终结果将是一个包含 4 个键值对的键 1 的字典。

为什么我在尝试实际构建字典时收到以下错误?

TypeError: unhashable type: 'collections.OrderedDict'

标签: pythondictionary

解决方案


您永远不会为dict. 假设nan,您的意思是 csv 中的空字段。您可以dict通过使用索引遍历具有索引的行来创建enumerate()

import csv

with open('test.csv') as fileo:
    reader = csv.DictReader(fileo)

    rec = {i:row for (i,row) in enumerate(reader) if row['COMMENT'] != ''}
    print(rec)

测试.csv

NAME,Colour,Type,COMMENT
 Apple,red,Fruit,Fuji
 Apple,green,Fruit,
 Apple,blue,Fruit,Kiwi

输出:

{0: OrderedDict([(' NAME', ' Apple'), ('Colour', 'red'), ('Type', 'Fruit'), ('COMMENT', 'Fuji')]), 
2: OrderedDict([(' NAME', ' Apple'), ('Colour', 'blue'), ('Type', 'Fruit'), ('COMMENT', 'Kiwi')])}

如果您想要连续索引,您可以使用单独的计数进行迭代。


推荐阅读