从输入构建字典(尚未找到我需要的部分的任何答案)

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

基本上,我想直接从输入创建单词和值的字典,而不使用频率或计数。我很确定我已经很接近了,但我不知道如何让它超过一组。这是我到目前为止的代码:

def build_dictionary(words):
    return{str(input()):str(int(input()))}
if __name__ == '__main__':
    words = input().split()
    your_dictionary = build_dictionary(words)
    sorted_keys = sorted(your_dictionary.keys())
    for key in sorted_keys:
        print(f'{key} - {str(your_dictionary[key])}')

我是否需要在某处使用 for 循环,或者除此之外我还需要做其他事情吗?

我尝试按原样运行它,最初让我输入一些似乎什么也不做的东西,然后是实际所需的输入,这对第一组有效,但后来就停在那里了。之后,我尝试在开始时的空白处输入所需的迭代次数,但得到了相同的最终结果。我希望让它按照输入指定的次数重复该过程。

python
2个回答
0
投票

如果您想根据用户输入多次重复此过程,可以使用 for 循环。

def build_dictionary(单词): 返回 {str(input()): str(int(input()))}

if name == 'main': 你的字典= {} 对于 _ 在范围内(num_iterations): 单词 = input().split() your_dictionary.update(build_dictionary(words))

sorted_keys = sorted(your_dictionary.keys())
for key in sorted_keys:
    print(f'{key} - {your_dictionary[key]}')

0
投票

你需要尝试并了解更多。但对于这个问题:

def build_dictionary(words):
    ret = dict()
    for word in words:
        if word not in ret:
            ret[word] = 1
        else:
            ret[word] += 1
    return ret


if __name__ == '__main__':
    words = input().split()
    your_dictionary = build_dictionary(words)
    sorted_keys = sorted(your_dictionary.keys())
    for key in sorted_keys:
        print(f'{key} - {your_dictionary[key]}')
© www.soinside.com 2019 - 2024. All rights reserved.