w3resource

Python: Create a dictionary from a string

Python dictionary: Exercise-24 with Solution

Write a Python program to create a dictionary from a string.

Note: Track the count of the letters from the string.

Sample Solution:

Python Code:

# Import the 'defaultdict' and 'Counter' classes from the 'collections' module.
from collections import defaultdict, Counter

# Create a string 'str1' containing characters.
str1 = 'w3resource'

# Create an empty dictionary 'my_dict' to store character counts.
my_dict = {}

# Iterate through the characters in the string 'str1' using a for loop.
for letter in str1:
    # Update the 'my_dict' by incrementing the count of the current character.
    # Use the 'get' method with a default value of 0 to initialize counts for new characters.
    my_dict[letter] = my_dict.get(letter, 0) + 1

# Print the 'my_dict' dictionary, which contains character counts.
print(my_dict) 
  

Sample Output:

{'w': 1, '3': 1, 'r': 2, 'e': 2, 's': 1, 'o': 1, 'u': 1, 'c': 1}

Python Code Editor:

Previous: Write a Python program to combine values in python list of dictionaries.
Next: Write a Python program to print a dictionary in table format.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/dictionary/python-data-type-dictionary-exercise-24.php