A question about dictionaries in an exercise

Hello.
I’m a beginner in python, I was trying to solve an exercise, in which I encountered a problem.
The exercise is finding the most repeated alphabet character in a sentence.
I have written this:

sentence = “This is a common interview question”

for char in sentence:
countingchar = sentence.count(char)
chardict = {char: countingchar}
print(chardict )

As you see I tried to create a dictionary containing every character of the sentence, however the result was multiple dictionaries with one key:value pair instead of one dictionary with multiple key:value pairs. My problem is that I can’t merge these dictionaries into one dictionary.
What should I do?
Can you help me finding a solution with this approach?
If I have written or missed any line of code please tell me.
I’m trying to understand and learn.

Appreciate you time and help.

1. Create the dictionary
2. Loop over the sentence
3. On every iteration, update the dictionary
4. After the loop is done, print your dictionary

Atm, you are doing

1. Loop over the sentence
2. On every iteration, create a dictionary and print it

So you want

create_thing > loop: populate_thing > print_thing

Not

loop: create_and_print_thing

1 Like

Thanks DanCouper,

sentence = “This is a common interview question”

chardict = {}
for char in sentence:
chardict.update({char: sentence.count(char)})

sorted_chardict = sorted(
chardict.items(), key=lambda item: item[1], reverse=True)
print(sorted_chardict)

and the result is correct.

Now I have another question:
Consider the previous code which was:
for char in sentence:
countingchar = sentence.count(char)
chardict = {char: countingchar}
print(chardict)

the result of this code is=
{‘T’: 1}
{‘h’: 1}
{‘i’: 5}
{‘s’: 3}
{’ ‘: 5}
{‘i’: 5}
{‘s’: 3}
{’ ‘: 5}
{‘a’: 1}
{’ ‘: 5}
{‘c’: 1}
{‘o’: 3}
{‘m’: 2}
{‘m’: 2}
{‘o’: 3}
{‘n’: 3}
{’ ‘: 5}
{‘i’: 5}
{‘n’: 3}
{‘t’: 2}
{‘e’: 3}
{‘r’: 1}
{‘v’: 1}
{‘i’: 5}
{‘e’: 3}
{‘w’: 1}
{’ ': 5}
{‘q’: 1}
{‘u’: 1}
{‘e’: 3}
{‘s’: 3}
{‘t’: 2}
{‘i’: 5}
{‘o’: 3}
{‘n’: 3}
we have 35 dictionaries, my question is that is it possible after the loop to merge all of these dictionaries into a single dictionary?
if yes, what should I do? what would be the approach for it?

As pointed out before, you do not have 35 dictionaries. You have a variable that you keep overwriting with one dictionary. The way you deal with this issue is to follow @DanCouper’s algorithm.