2016-08-11 10 views
0

{'2234': '1'、 '233': '60'} 次のような辞書を書きたいと思います。作成されました。 私はこれが答えたページを発見し、私は、Python 2.7でこれを試してみたが、これはまだ私のコードを実行しながら、私にエラーを与える:エラーとして私のために私は、コードを実行するとpythonでcsvファイルに辞書を書く2.7

with open('variabelen.csv', 'w') as csvfile: 
    writer = csv.writer(csvfile) 
    for name, items in a.items():  
     writer.writerow([name] + items) 

これが現れました:

Traceback (most recent call last): 
    File "/Users/Danny/Desktop/Inventaris.py", line 48, in <module> 
    Toevoeging_methode_plus(toevoegproduct, aantaltoevoeging) 
    File "/Users/Danny/Desktop/Inventaris.py", line 9, in Toevoeging_methode_plus 
    writecolumbs() 
    File "/Users/Danny/Desktop/Inventaris.py", line 24, in writecolumbs 
    writer.writerow([name] + items) 
TypeError: can only concatenate list (not "str") to list 

答えて

1

あなたは、文字列itemsでリスト[name]を連結している - ので、エラー。

代わりに、あなたは、単に.writerows()経由items()を書き込むことができます。しかし異なる場合があり

233,60 
2234,1 

行の順序:

with open('variabelen.csv', 'w') as csvfile: 
    writer = csv.writer(csvfile) 
    writer.writerows(a.items()) 

a = {'2234': '1', '233': '60'}の価値を考えると、それは次の内容のvariabelen.csvを生成しますPythonの原因辞書には、の順序付けられていないコレクションがあります。

+0

同じ方法でこれを転置することはできますか?例えば;カラム名として233と2234を持ち、それらの名前で値を集めますか?ありがとうございました! @alecxe – Pythoner1234