这应该是相当直接的,但我无法让它工作。我在下面有以下代码。
我有一个csv文件,在A列中,我有以下内容:
[11, 12, 14, 18, 19, 23, 43, 44]
在B栏中,我有以下内容:
[2, 2, 2, 2, 2, 2, 2, 2]
我的尝试是:
import numpy
import csv
import json
f = open('C:\filepath\m.csv', 'r+')
csv_f = csv.reader(f, delimiter=',', quotechar='"')
new_list = []
new_list_two = []
for row in csv_f:
new_list.append(row[0])
new_list_two.append(row[1])
new_list_two= map(int, new_list_two)
new_list= map(int, new_list)
a = str(numpy.mean(new_list))
b = str(numpy.mean(new_list_two))
c = new_list + new_list_two
以下代码将返回:
[11, 12, 14, 18, 19, 23, 43, 44, 2, 2, 2, 2, 2, 2, 2, 2]
我希望通过将代码添加到字典中并将输出添加到JSON文件中来获取我的代码:
[
{
"September": 11,
"medium-critical": 2
},
{
"September": 12,
"medium-critical": 2
},
{
"September": 14,
"medium-critical": 2
},
{
"September": 18,
"medium-critical": 2
},
{
"September": 19,
"medium-critical": 2
},
{
"September": 23,
"medium-critical": 2
},
{
"September": 43,
"medium-critical": 2
},
{
"September": 44,
"medium-critical": 2
},
{
"September": 20,
"medium-critical": 3
},
{
"September": 32,
"medium-critical": 3
},
{
"September": 33,
"medium-critical": 3
},
{
"September": 54,
"medium-critical": 3
},
{
"September": 57,
"medium-critical": 3
},
{
"September": 69,
"medium-critical": 3
},
{
"September": 70,
"medium-critical": 3
},
{
"September": 73,
"medium-critical": 3
},
{
"September": 58,
"medium-critical": 6
},
{
"September": 66,
"medium-critical": 6
},
{
"September": 100,
"medium-critical": 7
},
{
"September": 68,
"medium-critical": 9
},
{
"August": 23,
"medium-critical": 2
},
{
"August": 44,
"medium-critical": 2
},
{
"August": 19,
"medium-critical": 2
},
{
"August": 18,
"medium-critical": 2
},
{
"August": 43,
"medium-critical": 2
},
{
"August": 48,
"medium-critical": 2
},
{
"August": 53,
"medium-critical": 3
},
{
"August": 67,
"medium-critical": 3
},
{
"August": 20,
"medium-critical": 3
},
{
"August": 66,
"medium-critical": 3
},
{
"August": 34,
"medium-critical": 3
},
{
"August": 60,
"medium-critical": 3
},
{
"August": 75,
"medium-critical": 3
},
{
"August": 49,
"medium-critical": 3
}
]
我尝试通过for循环运行列表“c”但是无法使密钥分配正常工作。
这样的事情:
with open('C:\filepath\m.csv') as f:
mydict=dict(csv.reader(f))
mydict['mean b'] = b
mydict['mean a'] = a
mydict = [mydict]
print mydict
new_dict = {}
for i in mydict:
new_dict[]
with open('C:\filepath\jsonfile.json', 'w') as q:
json.dump(mydict, q)
有没有更好的方法来获得所需的输出?
答案 0 :(得分:3)
解决方案:
import csv
import json
json.dump([{'September': k, 'medium-critical': v}
for k, v in csv.reader(open('data.csv'))], open('data.json', 'w'))