python - 从 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'
解决方案
您永远不会为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')])}
如果您想要连续索引,您可以使用单独的计数进行迭代。
推荐阅读
- unit-testing - 如何在不使用 REPL 的情况下使用 Rascal jar 运行测试?
- nginx - 通过负载均衡器访问服务器时间歇性 403,无法弄清楚原因
- javascript - 使用 Firebase 更新文档字段时使用 Object.assign
- javascript - 如何在 vuex 日志中隐藏下一个状态和上一个状态?
- r - 订购功能无法正确订购
- python - Setting nested enum value as default parameter in class __init__
- mysql - I need some design where I can keep more than one value in one column
- python - The order of tests works perfect on python 2 but not on python 3
- c++ - unresolved external symbol CORBA server
- ios - ReactNative iOS UNUserNotificationCenter:实现 didReceiveNotificationResponse