Python 在循环中将记录添加到字典

Python 在循环中将记录添加到字典,python,dictionary,python-3.4,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[

我想通过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的结果字典时,我只能看到附加的最新记录。

您的配对字典有固定的“feature”和“themation”键,因此这些键在更新调用中会被覆盖

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

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

字典中每个键只能有一个值。也许字典列表更合适?使用
tweet
值(猜测其某种id)作为字典的键,然后将
dict作为值是否合理?