简体   繁体   中英

create dictionary from csv file using a key within row in python

How would i create a dictionary using a csv file if the key is the last index ( index[9] ) in every row. for example:

,,,,,,,,,KEY_1
,,,,,,,,,KEY_1
,,,,,,,,,KEY_1
,,,,,,,,,KEY_2
,,,,,,,,,KEY_2
,,,,,,,,,KEY_2
,,,,,,,,,KEY_3
,,,,,,,,,KEY_3
,,,,,,,,,KEY_3

Is there a way to create a dictionary that would look like this:

dictt = {
        'KEY_1':[,,,,,,,,], [,,,,,,,,], [,,,,,,,,],
        'KEY_2':[,,,,,,,,], [,,,,,,,,], [,,,,,,,,],
        'KEY_3':[,,,,,,,,], [,,,,,,,,], [,,,,,,,,],
        }

I only have 6mons of self taught python and I am working out the growing pains. Any help is greatly appreciated. thank you in advanced

In answer to your "is it possible" question, one must say "not quite", because no Python construct matches the syntax you show:

dictt = {
    'KEY_1':[,,,,,,,,], [,,,,,,,,], [,,,,,,,,],
    'KEY_2':[,,,,,,,,], [,,,,,,,,], [,,,,,,,,],
    'KEY_3':[,,,,,,,,], [,,,,,,,,], [,,,,,,,,],
    }

Entering this would be a syntax error, and no code can thus build the equivalent.

But if you actually mean, eg,

dictt = {
    'KEY_1':[['','',,,,,,,], [,,,,,,,,], [,,,,,,,,]],
    'KEY_2':[[,,,,,,,,], [,,,,,,,,], [,,,,,,,,]],
    'KEY_3':[[,,,,,,,,], [,,,,,,,,], [,,,,,,,,]],
    }

(and so on replacing each ,, to have something inside, eg an empty string -- not gonna spend a long time editing this to fix it!-), then sure, it is possible.

Eg:

import collections
import csv

dictt = collections.defaultdict(list)

with open('some.csv') as f:
    r = csv.reader(f)
    for row in r:
        dictt[r[-1]].append(r[:-1])

When this is done dictt will be an instance of collections.defaultdict (a subclass of dict ) but you can use it as a dict . Or if you absolutely insist on its being a dict and not a subclass thereof (though there is no conceivably good reason to thus insist), follow up with

dictt = dict(dictt)

and voila, it's converted:-)

Another way:

txt='''\
,,,,,,,,,KEY_1
,,,,,,,,,KEY_1
,,,,,,,,,KEY_1
,,,,,,,,,KEY_2
,,,,,,,,,KEY_2
,,,,,,,,,KEY_2
,,,,,,,,,KEY_3
,,,,,,,,,KEY_3
,,,,,,,,,KEY_3
'''

import csv

result={}
for line in csv.reader(txt.splitlines()):
    result.setdefault(line[-1], []).append(line[:-1])

>>> result
{'KEY_1': [['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', '']], 'KEY_3': [['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', '']], 'KEY_2': [['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', '']]}

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