简体   繁体   English

Python-从CSV创建字典词典

[英]Python - Create dictionary of dictionaries from CSV

I have a CSV with the first column having many duplicate values, and the second column being a predetermined code that maps to a value in the third column, such as this: 我有一个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

I'm trying to create a dictionary of dictionaries from a CSV, that would result in the following: 我正在尝试从CSV创建字典的字典,这将导致以下结果:

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

My code creates the key values just fine, but the resulting value dictionaries are all empty (though some print statements have shown that they aren't during the run process)... 我的代码可以很好地创建键值,但是结果值字典全为空(尽管某些打印语句表明它们不在运行过程中)...

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

You don't need dict2 and you are not setting it to be the value dict anyway. 您不需要dict2 ,也无论如何都不会将其设置为dict值。 Try this modified version: 试试这个修改后的版本:

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

You can also use defaultdict to skip checking for existing keys. 您也可以使用defaultdict跳过对现有密钥的检查。

Use collections.defaultdict for this. 为此使用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 is nothing more than a dictionary which initializes values for unknown keys with a default. defaultdict只是一个字典,该字典使用默认值初始化未知键的值。 Here, the default is to initialize a second, new dictionary ( dict is the dictionary constructor). 在这里,默认值是初始化第二个新字典( dict是字典的构造函数)。 Thus, you can easily set both mappings in the same line. 因此,您可以轻松地在同一行中设置两个映射。

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

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