简体   繁体   中英

How to read a 2d Dictionary from a csv file?

I have a CSV file and want to read the file to make a 2d dictionary.

I have tried creating a new dictionary:

f = csv.reader(open('test.csv', 'r'))
for row in f:
    k, v, p  = row 
    markovTransition[k] = {v: p}

The code above gives the output I want except It overwrites the key when the keys for the first dictionary are the same.

The CSV file is in the format of:

A,A1,3
A,A2,4
B,B1,6
C,C3,7
C,C2,3
C,C5,1

The desired dictionary is:

{A: {A1: 3, A2: 4}, B: {B1: 6}, C: {C3: 7, C2: 3, C5: 1}

The current dictionary is:

{A: {A2: 4}, B: {B1: 6}, C{C5: 1}}

How do I create a 2d dictionary from a CSV file? Thanks.

This is a nice use case for a defaultdict:

markovTransition=collections.defaultdict(dict)
f = csv.reader(open('test.csv', 'r'))
for row in f:
    k, v, p  = row 
    markovTransition[k][v] = p

try this:

markovTransition = {}
f = csv.reader(open('test.csv', 'r'))
for row in f:
    k, v, p  = row

    if k in markovTransition.keys():  # Check if already exists and then push it.
        markovTransition[k].update({v: p})
    else:
        markovTransition[k] = {v: p}

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