简体   繁体   English

用两个键将CSV转换为字典

[英]Convert CSV to dictionary with two keys

I'm a newbie who just started learning Python. 我是刚开始学习Python的新手。

I have a CSV file as following: 我有一个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

I'm trying to convert it into a Python dictionary, the optimal output should be something like this: 我正在尝试将其转换为Python字典,最佳输出应如下所示:

{food:{meat:[bacon,lamb],fruit:[apple, pear, banana, kiwi]},animal:{reptile:{[lizard,snake],mammal:[mouse,cat]}

My code: 我的代码:

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)

I tried codes like above and its variations, but it didn't work out. 我尝试了上面的代码及其变体,但没有成功。 I know that I might need to make two loops or so to make it work but I'm not sure how to make it. 我知道我可能需要进行两个循环左右才能使其工作,但是我不确定如何进行。

Thanks in advance! 提前致谢! And sorry if I'm using the wrong terms in the description. 抱歉,如果我在描述中使用了错误的术语。

Poppel Poppel

You are pretty close. 你很亲密 You need a dictionary of dictionary of list. 您需要列表字典的字典。

Try: 尝试:

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)

Output: 输出:

{'animal': {'mammal': ['mouse', 'cat'], 'reptile': ['lizard', 'snake']},
 'food': {'fruit': ['apple', 'pear', 'banana', 'kiwi'],
          'meat': ['bacon', 'lamb', 'beef']}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM