簡體   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