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

Question:

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"]

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?

Asked By: Laura

||

Answers:

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}
Answered By: Алексей Р