简体   繁体   中英

Convert CSV to dictionary with two keys

I'm a newbie who just started learning Python.

I have a CSV file as following:

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:

{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

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']}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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