Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check and store in dict number of repeating substrings and characters of a string python

I’m trying to find the number of substrings and characters of a given string comparing with a list and returning them in a dict, it doesn’t matter the order, like the example:

string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"

list = ["a","em","i","el"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

result = {‘a’: 7, ’em’: 2, ‘i’: 11, ‘el’: 1}

I’m doing the following code:

frequencies = {}
test_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
test_list = ["a","em","i","el"]
for char in test_list:
  for char in test_string:
    if char in test_list:
      if char in frequencies: 
        frequencies[char] += 1
      else: 
        frequencies[char] = 1
print(frequencies)

But this code only return the characters, like this:

{‘i’: 44, ‘a’: 28}

When it should return characters and substrings only once, like this:

{‘a’: 7, ’em’: 2, ‘i’: 11, ‘el’: 1}

How can I get the substrings and the characters from this string to a single dict at the same time?

>Solution :

Use .count() to count substring in the string and dict comprehension to make the dict

txt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
lst = ["a", "em", "i", "el"]

d = {k: txt.count(k) for k in lst}
print(d)
{'a': 7, 'em': 2, 'i': 11, 'el': 1}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading