Python - 从CSV创建词典字典

时间:2016-07-18 05:00:46

标签: python csv dictionary nested

我有一个CSV,第一列有许多重复值,第二列是预定代码,映射到第三列中的值,如下所示:

1, a, 24
1, b, 13
1, c, 30
1, d, 0
2, a, 1
2, b, 12
2, c, 82
2, d, 81
3, a, 04
3, b, 23
3, c, 74
3, d, 50

我尝试从CSV创建词典字典,这会产生以下结果:

dict 1 = {'1':{'a':'24', 'b':'13', 'c':'30','d':'0'}, 
          '2':{'a':'1', 'b':'12', 'c':'82','d':'81'}, 
          ... }

我的代码很好地创建了键值,但结果值字典全部为空(尽管一些打印语句显示它们在运行过程中不是)...

with open(file, mode='rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')

    dict1 = {}  # creates main dict
    for row in reader:  # iterates through the rows of the csvfile
        if row[0] in dict1:
            dict2[row[1]] = row[2]  # adds another key, value to dict2
        else:
            dict1[row[0]] = {}  # creates a new key entry for the new      dict1 key
            dict2 = {}  # creates a new dict2 to start building as the value for the new dict1 key
            dict2[row[1]] = row[2]  # adds the first key, value pair for dict2

2 个答案:

答案 0 :(得分:2)

您不需要dict2,并且您不会将其设置为值dict。试试这个修改过的版本:

with open(file, mode='rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')

    dict1 = {}  # creates main dict
    for row in reader:  # iterates through the rows of the csvfile
        if row[0] not in dict1:
            dict1[row[0]] = {}  # creates a new key entry for the new dict1 key
        dict1[row[0]][row[1]] = row[2]  # adds another key, value to dict2

您还可以使用defaultdict来跳过检查现有密钥。

答案 1 :(得分:2)

请使用collections.defaultdict

import collections

with open(file, mode='rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')

    dict1 = collections.defaultdict(dict)
    for row in reader:
        dict1[row[0]][row[1]] = row[2]

defaultdict只不过是一个用默认值初始化未知键值的字典。这里,默认是初始化第二个新字典(dict是字典构造函数)。因此,您可以轻松地在同一行中设置两个映射。