如何在 python 中为一个键存储多个值

how to store multiple values for one key in python

参数allWords包含两列和数千行。第一栏推文。第二个包含情绪(0 表示负面,4 表示正面。

如底部代码所示,我创建了两个词典(否定和肯定)来将单词及其出现频率存储在词典中。

如果你运行代码显示如下:

这是否定字典 {'transit': 1, 'infect': 4, 'spam': 6}

这是正字典 {'transit': 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 = {'transit': [1][3], 'infect': [4][5], 'spam': [6][2]}

第一个值代表负数。而第二个值是正值。如何实现?

我正要发表评论,但还不能这样做,所以我把它放在一个答案中:

这里的第一个答案可能会帮助您实现您想要的:

append multiple values for one key in Python dictionary

简而言之:你不需要使用数字作为键,你也可以使用数组,所以你最终得到:

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

因为我认为您想要的结构很奇怪而且没有意义,所以我将它们都放在一个列表中:

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]}

只需保留一对 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]

您可以使每个键的值成为它自己的具有 negativepositive 键的字典。因此,您修改后的字典将是

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

依此类推。

或者,您可以制作一个小 class 来存储负值和正值,并将其作为每个键的值。如果您的 class 看起来像:

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)