【问题标题】:Python - Create dictionary of dictionaries from CSVPython - 从 CSV 创建字典字典
【发布时间】:2016-11-20 14:21:26
【问题描述】:

我有一个 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 成为dict1 的一部分。

标签: python csv dictionary nested


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您不需要dict2,并且您也没有将其设置为值字典。试试这个修改后的版本:

    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 跳过检查现有密钥。

    【讨论】:

    • 迟到一分钟。 defaultdict 非常适合这个。
    • @MichaelHoff 我建议您取消删除您的答案(如果它有效),因为它通过代码示例演示了我的替代方法。
    • 你是对的。它仍然有助于回答这个问题,即使它有点多余。
    猜你喜欢
    • 2016-09-03
    • 1970-01-01
    • 2018-04-07
    • 2014-10-02
    • 2014-11-11
    • 1970-01-01
    • 2016-07-11
    • 2021-06-25
    • 2017-05-05
    相关资源
    最近更新 更多