2016-11-11 49 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))