繁体   English   中英

Python-从CSV创建字典词典

[英]Python - Create dictionary of dictionaries from CSV

我有一个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

您不需要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跳过对现有密钥的检查。

为此使用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是字典的构造函数)。 因此,您可以轻松地在同一行中设置两个映射。

暂无
暂无

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

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