简体   繁体   English

如何从csv文件读取2d词典?

[英]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. 我有一个CSV文件,想读取该文件以制作2D词典。

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: CSV文件的格式为:

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? 如何从CSV文件创建2d词典? Thanks. 谢谢。

This is a nice use case for a defaultdict: 这是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}

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

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