Python - 遍历整个列表并将其分配给dict

时间:2017-10-15 02:35:08

标签: python

text = "This is a test for my program"
new_dict = {}
text_list = text.split()

word_tester = 2
for word in text_list:
    word_tester = len(word)
    if len(word) == word_tester:
        new_dict[word_tester] = word

return new_dict

我正在尝试在python中构建一个程序,该程序通过一个字符串列表并将它们分配给一个字典,其中键是该字符串中的字符数量,值是单词本身 (例如:2:be,to 3:foo,bar)。然而,我的程序只会通过并分配一些给定的字符串列表。我该怎么做才能让它发挥作用?

4 个答案:

答案 0 :(得分:1)

我认为你只需要确保分割空间。我跑了这个,它有效。

text = "This is a test for my program"
text_list = text.split(" ")
new_dict = {}
for word in text_list:
    if len(word) in new_dict and word not in new_dict[len(word)]:
        new_dict[len(word)].append(word)
    else:
        new_dict[len(word)] = [word]

#print(new_dict)
#{1: ['a'], 2: ['is', 'my'], 3: ['for'], 4: ['This', 'test'], 7: ['program']}
return new_dict

答案 1 :(得分:0)

#1

text = "This is a test for my program"
final_dct = {len(word):word for word in text.split() if len(word)==len(word_tester)}

#2
text = "This is a test for my program"
new_dict = {}
text_list = text.split()


for word in text_list:
    if len(word) in new_dict and word not in new_dict[len(word)]:
        new_dict[len(word)].append(word)
    else:
        new_dict[len(word)] = [word]

return new_dict

答案 2 :(得分:0)

我认为这很简单:

for word in text_list:
    if len(word) in new_dict:
        new_dict[len(word)].append(word)
    else:
        new_dict[len(word)] = [word]

请注意,在此字典中,键4被分配给test而不是this,因为每个键只能分配一个值。要在这种情况下使值成为列表,您可以使用:

{{1}}

答案 3 :(得分:0)

问题是一个键只能有一个值,所以每次有一个给定长度的单词时都要覆盖它。要解决此问题,您可以将字符串列表存储为字典值而不是单个字符串,如另一个示例所示。

collections模块中的一个便捷工具是defaultdict,它允许您在密钥尚未具有值时定义默认条目。一个常见的用例是使用defaultdict(list)使用空列表启动密钥。这使您无需检查密钥是否仍然存在,并手动将其初始化为空列表。将此结合到您的示例中,您将获得:

from collections import defaultdict

text = "This is a test for my program"
new_dict = defaultdict(list) # a dictionary whose default value is an empty list
text_list = text.split()

for word in text_list:
    # append this word to the list of words with the same length
    new_dict[len(word)].append(word)

return new_dict