将字典列表写入多列(和行)

时间:2017-06-01 16:40:56

标签: python csv

我有一个长度为[{"description":"Lorem, ipsum, dolor, sit amet","error":"text_too_long"},{'description':'Sed ut perspiciatis, unde omnis','error':'text_too_long'},...] 的词典列表。典型的内容是:

import csv, ast
list_ = list_of_dictionaries #as a string
with open('data.csv','wb') as f:
    wtr = csv.writer(f)
    for string in list_:
        dictionary = ast.literal_eval(string) #converting to dictionary
        to_write = [dictionary["description"],dictionary["error"]]
        wtr.writerow([to_write])

我试图将其写入CSV文件,其中" description"和"错误"形成两列,行是列表中的每个元素。

我试过了:

/home/akhil/anaconda2/lib/python2.7/site-
packages/oauth2client/_helpers.py:255: UserWarning: Cannot access 
storage.json: No such file or directory
warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
Traceback (most recent call last):
File "/home/akhil/Desktop/TIME_SCHEDULE_UPDATER/quickstart.py", line 
16, in <module>
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
File "/home/akhil/anaconda2/lib/python2.7/site-
packages/oauth2client/_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "/home/akhil/anaconda2/lib/python2.7/site-
packages/oauth2client/client.py", line 2134, in 
flow_from_clientsecrets
cache=cache)
File "/home/akhil/anaconda2/lib/python2.7/site-
packages/oauth2client/clientsecrets.py", line 165, in loadfile
return _loadfile(filename)
File "/home/akhil/anaconda2/lib/python2.7/site-
packages/oauth2client/clientsecrets.py", line 126, in _loadfile
return _validate_clientsecrets(obj)
File "/home/akhil/anaconda2/lib/python2.7/site-
packages/oauth2client/clientsecrets.py", line 101, in 
_validate_clientsecrets
prop_name, client_type))
oauth2client.clientsecrets.InvalidClientSecretsError: Missing property 
"redirect_uris" in a client type of "web".

这只是给我一个列中的整个字典(但行很好)。我做错了什么?

2 个答案:

答案 0 :(得分:1)

你能否使用"scripts": { "dev": "webpack-dev-server --hot --inline --open --watch" },

pandas

你明白了:

data = [{"description":"Lorem, ipsum, dolor, sit amet","error":"text_too_long"},{'description':'Sed ut perspiciatis, unde omnis','error':'text_too_long'}]

import pandas as pd

df = pd.DataFrame(data)

然后使用df Out[246]: description error 0 Lorem, ipsum, dolor, sit amet text_too_long 1 Sed ut perspiciatis, unde omnis text_too_long

to_csv

答案 1 :(得分:1)

可以直接设置词典,不需要ast功能。

for dictionary in list_:
    to_write = [dictionary["description"],dictionary["error"]]
    wtr.writerow(to_write) # Not [to_write]

将字典写成2列。