2016-11-11 47 views
-1

我正在使用Python 2.7並嘗試將一個浮點值插入到一個鍵中。但是,所有值都被插入爲0.0。極性值被插入爲0.0而不是實際值。Python 2.7字典值沒有采用float作爲輸入

代碼段:

from textblob import TextBlob 
import json 
with open('new-webmd-answer.json') as data_file: 
data = json.load(data_file, strict=False) 
data_new = {} 
lst = [] 
for d in data: 
    string = d["answerContent"] 
    blob = TextBlob(string) 
#print blob 
#print blob.sentiment 
#print d["questionId"] 
    data_new['questionId'] = d["questionId"] 

    data_new['answerMemberId'] = d["answerMemberId"] 
    string1 = str(blob.sentiment.polarity) 
    print string1 
    data_new['polarity'] = string1 
#print blob.sentiment.polarity 
    lst.append((data_new)) 




json_data = json.dumps(lst) 

#print json_data 
with open('polarity.json', 'w') as outfile: 
    json.dump(json_data, outfile) 
+0

每個迭代一個新的字典,當你打印你看到預期的輸出字符串1?此外,它看起來像覆蓋字典中的密鑰,每次迭代'd in data' – user2682863

+0

@ user2682863是的,當我打印字符串1時,我看到了預期的輸出。是的,我覆蓋了鑰匙。在我覆蓋之前,我還將它添加到列表中。 –

+0

我的答案是否解決了您的問題? – user2682863

回答

0

你的代碼是目前編寫方式,你是覆蓋在每次迭代的字典。然後,您將該字典多次添加到列表中。

可以說你的字典是dict = {"a" : 1},然後您可以附加到一個列表

alist.append(dict) 

alist 

[{ 'A':1}]

然後你改變字典的值,dict{"a" : 0}並將它附加到再次alist.append(dict)

alist

[{ 'A':0},{ 'A':0}]列表

這是因爲字典是可變的。有關可變VS unmutable對象看到文檔here

實現你預期的輸出更完整的概述,請與data

lst = [] 
for d in data: 
    data_new = {} # makes a new dictionary with each iteration 
    string = d["answerContent"] 
    blob = TextBlob(string) 
    # print blob 
    # print blob.sentiment 
    # print d["questionId"] 
    data_new['questionId'] = d["questionId"] 

    data_new['answerMemberId'] = d["answerMemberId"] 
    string1 = str(blob.sentiment.polarity) 
    print string1 
    data_new['polarity'] = string1 
    # print blob.sentiment.polarity 
    lst.append((data_new))