我是一个刚开始学习 Python 的新手。
我有一个 CSV 文件如下:
theme,type,name
food,meat,bacon
food,meat,lamb
food,meat,beef
food,fruit,apple
food,fruit,pear
food,fruit,banana
food,fruit,kiwi
animal,reptile,lizard
animal,reptile,snake
animal,mammal,mouse
animal,mammal,cat
我正在尝试将其转换为 Python 字典,最佳输出应该是这样的:
{food:{meat:[bacon,lamb],fruit:[apple, pear, banana, kiwi]},animal:{reptile:{[lizard,snake],mammal:[mouse,cat]}
我的代码:
import csv
testDict={}
with open('file.CSV','r') as f:
tempDict = csv.DictReader(f)
for getPKvalue in tempDict:
testDict.setdefault(getPKvalue['theme'],[]).append(getPKvalue['type'])
print(testDict)
我尝试了上面的代码及其变体,但没有成功。我知道我可能需要做两个循环才能使其工作,但我不确定如何制作。
提前致谢!很抱歉,如果我在描述中使用了错误的术语。
波佩尔
你很接近。你需要一个列表字典字典。
尝试:
import csv
testDict = {}
with open(filename) as f:
tempDict = csv.DictReader(f)
for row in tempDict:
testDict.setdefault(row['theme'],{}).setdefault(row['type'], []).append(row['name'])
print(testDict)
输出:
{'animal': {'mammal': ['mouse', 'cat'], 'reptile': ['lizard', 'snake']},
'food': {'fruit': ['apple', 'pear', 'banana', 'kiwi'],
'meat': ['bacon', 'lamb', 'beef']}}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句