将列表添加到词典

问题描述 投票:-2回答:2

我需要将电影评论的分数与评论行的每个单词配对。例如,如果审核行是"3 I love this movie"。然后字典应该有:

dict = {3:I, 3:love, 3:this, 3:movie}

这是我的代码:

#function to pair every single word with the score attributed to the review.

def pair_word_with_score(user_input):
    #create a dictionary
    pair_dict = {}
    words = user_input.split()
    for word in words:
        pair_dict[words[0]] = word
    return pair_dict



def main():
    user_input = input("Please enter a review \n")
#call the pairing function
    print(pair_word_with_score(user_input))
if __name__ == "__main__":
    main()

当我调用该函数时,它只打印{3:movie}。其他值被覆盖。

python python-3.x dictionary
2个回答
0
投票
def pair_word_with_score(user_input):
    #create a dictionary
    pair_dict = {}
    words = user_input.split()
    for word in words:
        pair_dict[word] = words[0]
    return pair_dict



def main():
    user_input = input("Please enter a review \n")
#call the pairing function
    print(pair_word_with_score(user_input))
if __name__ == "__main__":
    main()

现在你可以得到我:3爱:3和其他如果你有相同的单词,如“我喜欢它”,你尝试编写代码,如添加到3并创建列表[3,4],这样你就可以计算出多少评论爱就是那样的


1
投票

字典只能有唯一的键,这意味着您无法创建:

3 : 'I'
3 : 'love'
...

在这种情况下,3是键,'I'是一个值。

我想你想要有关系:

number -> list_of_words

以下是如何从以下句子创建字典:3是键,单词是值:

>>> text = "3 I love this movie"
>>> my_dict = dict(zip([int(text[0])], [text[1:].split()]))
>>> my_dict
{3: ['I', 'love', 'this', 'movie']}

dict代表字典的构造函数,在这种情况下,它将元组转换为键,值对。

zip将两个可迭代对象(在本例中为列表)组合成元组。

如果要将键作为数字,则需要将第一个字符转换为int()类型

[1:]表示我正在读取除第一个字符之外的所有字符 - 它返回索引0处没有项目的列表

split()函数用分隔符分隔字符串中的单词(在这种情况下是空格,它是默认的分隔符)。它返回单词列表。

现在你可以打电话:

>>> my_dict[3]

你明白了

['I', 'love', 'this', 'movie']

你可以这样做(更具可读性):

>>> my_dict = {}
>>> my_dict[int(text[0])] = text[1:].split()
>>> my_dict
{3: ['I', 'love', 'this', 'movie']}

不要使用“dict”作为变量名,因为你的影子名称“dict()”代表字典构造函数。

© www.soinside.com 2019 - 2024. All rights reserved.