About Python Dictionary Output

Asked 2 years ago, Updated 2 years ago, 18 views

I'm a beginner in programming.
I am studying python using checkiO.

"Enter str and list.Write a function that outputs the number of words specified in the list in the sentence entered in str in dictionary form.

For example,
'When I was one I had just been when I was two I was nearly new'', ['i', 'was', 'three', 'near']))
If specified, the output is
{'i':4, 'was':3, 'three':0, 'near':0}
will be

I wrote the following program using the hint as a reference.

def popular_words (text:str, words:list) - > dict:
    text_list = text.split()
    answer={}
    for character in words:
        answer [character] = text_list.count (character)
    return answer

I don't understand line 5 of this program.
I understand text_list.count(character), but I don't understand why I have to put answer [character] on the left and what role it plays.
I also find it strange that only this line can print the answer dictionary type.

I'm sorry to ask you a rudimentary question, but I'd appreciate it if you could let me know.

python

2022-09-30 18:55

1 Answers

 answer={}

First of all, here's where answer is {}.
The dictionary type can be written like {key1:value1,key2:value2,...}, so {} is a blank dictionary.
Therefore, anwser is a dictionary type.

Now, if you want to add contents to the dictionary type, dict[key] = You can write value.
In this case, add the key:value to the dictionary dict.
(If key or value is a variable, it will be expanded and used.)

 answer [character] = text_list.count(character)

So if you write like above, you can add the contents to the dictionary.


2022-09-30 18:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.