2017-08-30 13 views
0

辞書値のリストを抽出して、csvに書き込むことができます。Dictsのリストの値 - Python 3

この前の情報を使用して、SO questionすべてのキー値をレプリケートしようとしています。

In [41]: dicts = [ 
    ...: {"name": "Tom", "age": 10}, 
    ...: {"name": "Mark", "age": 5}, 
    ...: {"name": "Pam", "age": 7}, 
    ...: {"name": "Dick", "age": 12}, 
    ...: ] 

しかし、私が得ている出力は非常に混ざり合っています。時にはそれがdictであり、時には値です。

In [25]: for item in dicts: 
    ...:  for k, v in item.items(): 
    ...:   print("Key: {0} and Value: {1}".format(k,v)) 
    ...: 
    ...: 
Key: name and Value: {'name': 'Dick', 'age': 12, 0: {...}} 
Key: age and Value: 10 
Key: 0 and Value: {'name': 'Dick', 'age': 12, 0: {...}} 
Key: name and Value: Mark 
Key: age and Value: 5 
Key: name and Value: Pam 
Key: age and Value: 7 
Key: name and Value: Dick 
Key: age and Value: 12 
Key: 0 and Value: {'name': 'Dick', 'age': 12, 0: {...}} 

出力にすべてのキーと値が抽出されていないようにしたいと思います。これを行うにはより良い方法がありますが、ipythonに誤って貼り付けるというエラーがありました。予想通り

編集 更新Dicts が更新Dictsで仕事を 出力を行います更新しました。

In [49]: for item in dicts: 
    ...:  for k, v in item.items(): 
    ...:   print("Key: {0} and Value: {1}".format(k,v)) 
    ...: 
Key: name and Value: Tom 
Key: age and Value: 10 
Key: name and Value: Mark 
Key: age and Value: 5 
Key: name and Value: Pam 
Key: age and Value: 7 
Key: name and Value: Dick 
Key: age and Value: 12 
+2

私はあなたの出力を再現することはできません。私は何の言葉も得ていない。 –

+1

あなたの 'dicts'はほぼ確実に壊れています。 – TemporalWolf

+4

再生できません。私はあなたが何をすべきか、むしろあなたが期待すべきものを得ています。 –

答えて

1

理由だけではなく、リストの上に列挙した値を抽出していない:あなたは再構築でき

for i, entry in enumerate(dicts): 
...    print entry['name']," ",entry['age'] 

そして値が

with open('dict.csv', 'wb') as csv_file: 
...   writer = csv.writer(csv_file) 
...   for i, entry in enumerate(dicts): 
...    writer.writerow([entry['name'],entry['age']]) 
+1

私はpython3を使用していますので、エメルテートは良いですが、列挙型(dicts)のエントリを使って作業しています: print( "{0}、{1}"形式(エントリ['name']、年齢'])) – sayth

1

csvファイルに書き込むことができますあなたのニーズを満たすために:

dicts = [{'key': k, 'value': v} for item in dicts for k,v in item.items()] 

for item in dicts: 
    print("Key: {key} and Value: {value}".format(**item)) 

しかし、CSVに直接それらを書くために、より良い方法があります:

import csv 

dicts = [{'key': k, 'value': v} for item in dicts for k,v in item.items()] 

with open('dicts.csv', 'wb') as f: 
    dict_writer = csv.DictWriter(f, dicts[0].keys()) 
    dict_writer.writeheader() 
    dict_writer.writerows(dicts) 
関連する問題