首页 > 解决方案 > 在python中以句子的单词作为键,单词从1开始的位置数作为值构建字典

问题描述

我希望从下面的代码中得到这个输出:

{'Tell': 1, 'a': 2, 'little': 3, 'more': 4, 'about': 5, 'yourself': 6, 'as': 7, 'a': 8, 'developer': 9}

但我得到这个输出:

{'Tell': 1, 'a': 8, 'little': 3, 'more': 4, 'about': 5, 'yourself': 6, 'as': 7, 'developer': 9}

这是代码:

sentence = 'Tell a little more about yourself as a developer'
list_words = sentence.split()

d = {word: i for i, word in enumerate(list_words, 1)}

print(d)

你认为是什么问题?给出我想要的输出的代码是什么?

标签: pythondictionary

解决方案


您不能在字典中有两个相同的键,因此不可能在“a”出现两次的情况下获得预期的结果(一次用于“a”:2,再次用于“a”:8)。

您输出的数据结构可以是元组列表而不是字典:

r = [(word,i) for i,word in enumerate(list_words,1)]

[('Tell', 1), ('a', 2), ('little', 3), ('more', 4), ('about', 5), 
 ('yourself', 6), ('as', 7), ('a', 8), ('developer', 9)]

或者,它可以是一个字典,其中包含每个单词的位置列表:

d = dict()
for i,word in enumerate(list_words,1):
    d.setdefault(word,[]).append(i)

{'Tell': [1], 'a': [2, 8], 'little': [3], 'more': [4], 
 'about': [5], 'yourself': [6], 'as': [7], 'developer': [9]}

推荐阅读