maurobio maurobio - 1 year ago 173
Python Question

python - How to create a dctionary from a CSV string

I have some comma-separated strings as follows:

filename1,12345,ABC
filename2,6789,CDE
filename3,999,GHI
...
etc.


I want to build a dictionary from these data, using the first column (a filename) as key and the rest of the data as a list of attributes (which may be size, date of last access, etc.), as

{'filename1': ['12345','ABC'], 'filename2': ['6789','CDE'], 'filename3':['999','GHI']}


The data do not include a header line and each line is a csv-string built in code and not read from a file.

I tried something like this:

import csv

s = """
filename1,12345,ABC
filename2,6789,CDE
filename3,999,GHI
"""

reader_list = csv.DictReader(s.splitlines())
for row in reader_list:
print row


which returns this:

{None: ['filename1', '12345', 'ABC']}
{None: ['filename2', '6789', 'CDE']}
{None: ['filename3', '999', 'GHI']}


but I could not figure a way of creating the key using the filename.

Any hints?

Answer Source

You don't need the csvmodule for this:

>>> s = """
filename1,12345,ABC
filename2,6789,CDE
filename3,999,GHI
"""
>>> d = {}
>>> for line in s.splitlines():
    if line:
        parts = line.split(',')
        key, attributes = parts[0], parts[1:]
        d[key] = attributes
>>> print d
{'filename1': ['12345', 'ABC'], 'filename2': ['6789', 'CDE'], 'filename3': ['999', 'GHI']}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download