简体   繁体   中英

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:

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:

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. 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.

Use collections.defaultdict for this.

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. Here, the default is to initialize a second, new dictionary ( dict is the dictionary constructor). Thus, you can easily set both mappings in the same line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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