我將開始我要說的話:「我是一個使用可怕'數據庫'的noob」。下面是我的csv當前json輸出的結構(下面的輪廓)。本質上,我試圖做的是將A(信息技術)欄中的「組」添加到每個「數據」字典中,因此有一個「組」鍵:值看起來像「組」:「信息技術」。然後,第5行(可選消費品)下的所有內容都將具有「組合」:「消費者自主選擇」鍵值。CSV到JSON Python,將組類別附加到詞典
{
"stocks": [
{
"data": {
"portfolio_average_weight": "5.985"
"portfolio_total_return": "27.948"
},
"name": "Google Inc "
},
{
"data": {
"portfolio_average_weight": "2.896",
"portfolio_total_return": "24.292"
},
"name": "Mastercard Inc "
}]
}
Column A Column B Column C Column D
Information Technology [blank cell] [blank cell] [blank cell]
[blank cell] Google 5.985 27.948
[blank cell] Mastercard 2.896 24.292
Consumer Discretionary [blank cell] [blank cell] [blank cell]
[blank cell] xxxxxx xxxxxxxxx xxxxxxxxx
這裏是我當前的代碼:
with open('test.csv', 'rU') as csvfile:
lines = csv.reader(csvfile)
for line in lines:
elif line[0] == "" and line[1] != "":
data = test_two_level(line)
bottom_level = {
"name": line[2],
"data": data}
def test_two_level(line):
data = {
"portfolio_average_weight":line[3],
"portfolio_total_return":line[4]}
return data
我想最終的輸出是什麼樣子:
{
"stocks": [
{
"data": {
"portfolio_average_weight": "5.985",
"portfolio_total_return": "27.948",
"group": "Information Technology"
},
"name": "Google Inc "
},
{
"data": {
"portfolio_average_weight": "2.896",
"portfolio_total_return": "24.292",
"group": "Information Technology"
},
"name": "Mastercard Inc "
}]
}
下面是CSV:
Information Technology,,,
,Google Inc ,5.985,27.948
,Mastercard Inc ,2.896,24.292
Consumer Discretionary,,,
你可以添加你的Python代碼,你正在閱讀的CSV到JSON? – Drewness
因此,字典已經存在,您想通過csv文件讀取並在字典的「庫存」列表中添加一個「組名」,該列表的名稱值與「列B」匹配的csv? – martineau
@martineau我想將列A中的「組」添加到每個股票的「數據」字典中。所以理想情況下,它看起來是我添加到我的原始文章底部 – user3208620