python - 循环添加记录到字典中

标签 python dictionary python-3.4

我想通过 for 循环将记录添加到字典中。我在堆栈溢出中看到了与此相关的问题。但我无法找出合适的方法。

我正在使用以下代码

inpTweets = csv.reader(open('C:/Twitter_crawl/training_sample.csv', 'r'), delimiter=',', quotechar='|')
    pair={}
    result={}
for row in inpTweets:
    sentiment = row[0]
    tweet = row[1]
    featureVector = getFeatureVector(tweet)
    pair={'feature':featureVector,'sentiment':sentiment}
    result.update(pair)

但是,当我访问名为 result 的结果字典时,我只能看到附加的最新记录。

最佳答案

您的配对字典具有“特征”和“情感”的固定键,因此这些键会在更新调用中被覆盖。

您可以使用字典列表来解决此问题:

pairs = [ ]
for row in inpTweets:
    sentiment = row[0]
    tweet = row[1]
    featureVector = getFeatureVector(tweet)
    pair={'feature':featureVector,'sentiment':sentiment}
    pairs.append(pair)

关于python - 循环添加记录到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30099646/

相关文章:

python - 从 PySpark 中的数据框中删除重复项

python - 如何使用新的 api 权限显示简单的 Instagram feed

python - 使用 itemgetter() 方法根据元组的第二个值在字典中查找键值对

LINQ 将字典转换为查找

python - Gtk.Grid 中小部件的大小

python - 是否可以获得列表成员的指针?

python - Google App Engine 在按钮点击时重定向到用户登录

python - 使用 Python 解释器时,如何在脚本运行之前执行一堆 Python 命令?

arrays - 从 TicketMasters API 中提取数据 (Swift 4.0/Decodable)

docker - Python3 utf8 编解码器在 Docker ubuntu 中未按预期解码 :trusty