Reputation: 607
I want to import a CSV into multiple dictionaries in python
queryInclude,yahoo,value1
queryInclude,yahoo,value2
queryInclude,yahoo,value3
queryExclude,yahoo,value4
queryExclude,yahoo,value5
queryInclude,google,value6
queryExclude,google,value7
My ideal result would have row[0]=dictionary, row[1]=key, and row[2]=value or list of values
queryInclude = {
"yahoo": ["value1", "value2", "value3"],
"google": ["value6"] }
queryExclude = {
"yahoo": ["value4", "value5"],
"google": ["value7"] }
Here's my code:
import csv
queryList=[]
queryDict={}
with open('dictionary.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in reader:
queryDict[row[1]] = queryList.append(row[2])
print queryDict
{'yahoo': None}
{'yahoo': None}
{'yahoo': None}
{'yahoo': None}
{'yahoo': None}
{'google': None, 'yahoo': None}
{'google': None, 'yahoo': None}
I have the flexibility to change the CSV format if needed. My ideal result posted above is what I already had hard-coded into my app. I'm trying to make it easier to add more values down the road. I've spent many hours researching this and will continue to update if I make any more progress. My thought process looks like this... not sure how close I am to understanding how to structure my loops and combine like values while iterating through the CSV rows...
for row in reader:
where row[0] = queryInclude:
create a dictionary combining keys into a list of values
where row[0] = queryExclude:
create a dictionary combining keys into a list of values
Upvotes: 4
Views: 739
Reputation: 161
Is this helping?
import StringIO
import csv
csvfile = StringIO.StringIO("""queryInclude,yahoo,value1
queryInclude,yahoo,value2
queryInclude,yahoo,value3
queryExclude,yahoo,value4
queryExclude,yahoo,value5
queryInclude,google,value6
queryExclude,google,value7""")
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
dict1={}
for row in reader:
key1, provider, value1 = row
if not dict1.has_key(key1):
dict1[key1] = {}
if not dict1[key1].has_key(provider):
dict1[key1][provider] = []
dict1[key1][provider].append(value1)
Upvotes: 2
Reputation: 177891
Using defaultdict
prevents having to account for the first element added to a dictionary. It declares the default type when the key is not present and must be a callable that creates the default object:
#! python3
import csv
from io import StringIO
from collections import defaultdict
from pprint import pprint
data = StringIO('''\
queryInclude,yahoo,value1
queryInclude,yahoo,value2
queryInclude,yahoo,value3
queryExclude,yahoo,value4
queryExclude,yahoo,value5
queryInclude,google,value6
queryExclude,google,value7
''')
D = defaultdict(lambda: defaultdict(list))
for d,k,v in csv.reader(data):
D[d][k].append(v)
pprint(D)
Output:
{'queryExclude': {'google': ['value7'],
'yahoo': ['value4', 'value5']},
'queryInclude': {'google': ['value6'],
'yahoo': ['value1', 'value2', 'value3']}}
Upvotes: 4