2016-03-07 133 views
0

參數allWords包含兩列和數千行。第一列推文。第二個包含一個情緒(0陰性和4爲陽性。如何在python中存儲一個鍵的多個值

作爲底部代碼顯示我已經創建了兩個字典(負&正),以在字典中的字存儲與它們的頻率。

如果運行代碼它顯示因爲它遵循:

這是負字典{「過境」:1,「傳染」:4,「垃圾郵件」:6}

這是爲正字典{'中轉':3,'infect':5,'spam':2}

def vectorRepresentation(allWords):  
    negative = {} 
    positive = {} 

    for (t,s) in allWords: 
     if(s=='0'): 
      for w in t: 
       if w in negative: 
        negative[w]+=1 
       else: 
        negative[w]=1 
     if(s=='4'): 
      for w in t: 
       if w in positive: 
        positive[w]+=1 
       else: 
        positive[w]=1 
    print(negative) 
    print(positive) 

但是,我想創建一個字典並存儲同一個鍵的兩個值。例如

newDictionary = { '過境':[1] [3], '傳染':[4] [5], '垃圾郵件':[6] [2]}

第一個值表示否定的。而第二個值是積極的。怎樣才能做到這一點?

+1

您可以修改您的預期輸出結構。就目前而言,這沒有多大意義。這在語法上是不正確的:'[1] [3]'你想如何將它存儲在你的字典中。你是否想要這樣做,也許:'[1,3]'? – idjaw

+0

簡答題:字典中每個鍵的值都是_something_,可以包含您想要跟蹤的所有信息。它可以是一個'dict','list','tuple','defaultdict','namedtuple',自定義類的對象,......你的名字。選擇什麼取決於你的日期會有多少。真的,你應該按照這個順序瞭解所有這些,並且根據你的需要來使用它們。 – alexis

回答

0

當我想到的結構,你婉t是奇怪,不要什麼意義,我把它們都在一個列表:

neg = {'transit': 1, 'infect': 4, 'spam': 6} 
pos = {'transit': 3, 'infect': 5, 'spam': 2} 
result = {} 
for k,v in neg.items(): 
    result[k] = [v,pos[k]] 
result # {'spam': [6, 2], 'transit': [1, 3], 'infect': [4, 5]} 
+1

謝謝你的時間。它的工作原理 – danny

1

我要發表評論,但不能這樣做,還讓我把它放在一個答案:

這裏的第一個答案可以幫助你實現你想要的:

append multiple values for one key in Python dictionary

簡而言之:你並不需要使用數字鑰匙,你也可以使用數組,所以你最終:

newDictionary = {'transit': [1,3], 'infect': [4,5], 'spam': [6,2]} 
+0

這是一個非常好的答案,你爲什麼要發表評論? – alexis

+0

,因爲它是在被別人鏈接的問題之前發佈的,所以回答鏈接問題的人應該獲得信用? – Valjean

0

只要保持一對int爲每個鍵的值。一個defaultdict將幫助你擺脫一些顛簸的:

from collections import defaultdict 

def vector_representation(all_words): 
    neg, pos = 0, 1 
    neg_pos = defaultdict(lambda: [0, 0]) # store two values for each key 

    for (t, s) in all_words: 
     if (s == '0'): 
      for w in t: 
       neg_pos[w][neg] += 1 
     if (s == '4'): 
      for w in t: 
       neg_pos[w][pos] += 1 
    return neg_pos 

d = vector_representation(...) 

d['transit'] 
>>> [1, 3] 

d['infect'] 
>>> [4, 5] 
+0

結果是什麼樣的? – Arman

1

你可以把對每個鍵的值它自己的字典,有一個negativepositive關鍵。所以,你的修改字典將是

{'transit': {'negative': 1, 'positive': 3}} 

等等等等。

或者,您可以創建一個存儲負值和正值的小類,並將其作爲每個鍵的值。如果您的類看起來像:

class NegativePositiveStore: 
    def __init__(self): 
     self.negative = 0 
     self.positive = 0 

你值將那麼所有是對象的不同實例。你可以這樣做:

word_dict = {} 
for (t,s) in allWords: 
    for w in t: 
     if w in word_dict: 
      if (s == '0'): 
       word_dict[w].negative += 1 
      elif (s == '4'): 
       word_dict[w].positive += 1 
     else: 
      word_dict[w] = NegativePositiveStore() 

print(word_dict)