4

CSVをPythonの複数の辞書にインポートしたい

queryInclude,yahoo,value1
queryInclude,yahoo,value2
queryInclude,yahoo,value3
queryExclude,yahoo,value4
queryExclude,yahoo,value5
queryInclude,google,value6
queryExclude,google,value7

私の理想的な結果は、row [0] =辞書、row [1] =キー、row[2]=値または値のリストになります。

queryInclude = {
        "yahoo": ["value1", "value2", "value3"],
        "google": ["value6"] }
queryExclude = {
        "yahoo": ["value4", "value5"],
        "google": ["value7"] }

これが私のコードです:

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}

必要に応じてCSV形式を柔軟に変更できます。上に投稿した私の理想的な結果は、すでにアプリにハードコーディングしたものです。今後、さらに価値を追加しやすくしようとしています。私はこれを研究するのに何時間も費やしました、そして私がさらに進歩するならば更新し続けるでしょう。私の思考プロセスは次のようになります...CSV行を反復処理しながら、ループを構造化し、同様の値を組み合わせる方法を理解するのにどれだけ近づいているかわかりません...

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
4

2 に答える 2

4

を使用defaultdictすると、辞書に追加された最初の要素を考慮する必要がなくなります。キーが存在しない場合はデフォルトのタイプを宣言し、デフォルトのオブジェクトを作成する呼び出し可能である必要があります。

#! 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)

出力:

{'queryExclude': {'google': ['value7'],
                  'yahoo': ['value4', 'value5']},
 'queryInclude': {'google': ['value6'],
                  'yahoo': ['value1', 'value2', 'value3']}}
于 2013-01-17T04:03:42.437 に答える
2

これは役に立ちますか?

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)
于 2013-01-17T03:57:46.830 に答える