2015-05-14 88 views
-1

我並不對該等數據的嵌套JSON追加在Python不能鍵值嵌套JSON在Python

products = {} 
results_hash = {} 
variations_hash = {} 
varaitions_array = [] 
variations_hash = varaitions_array 
results_array = variations_hash 

products["results"] = results_hash 
products["results"]["variations"] = variations_hash 

fname = "mouna" 
lname = "raj" 

sname = "kumar" 
slname = "vel" 

variations_hash[fname] = lname 
variations_hash[sname] = slname 

print products 

錯誤:

Traceback (most recent call last): 
    File "json_test.py", line 17, in <module> 
    variations_hash[fname] = lname 
TypeError: list indices must be integers, not str 

預期輸出:

{'results': {'variations': [{'Mouna': 'raj'} 
,{'kumar': 'vel'} 
]}} 

腳本中將做什麼修改

+0

您的'variations_hash'似乎是一個不是字典的列表。您的示例輸出中也一樣。列表是用整數索引的,而不是用字符串(比如'「mouna」')。 –

回答

1
 
Due to the line: variations_hash = varaitions_array 
variations_hash is now a list and not a dictionary any more. 
Hence, the error. 
0

由於variations_hash是一個列表,而不是一個字典,所以您可能需要循環訪問列表,然後獲取密鑰。