Python counter and dictionary intersection example

When it is required to demonstrate a counter and dictionary intersection, the Counter and dictionary can be used.

Below is the demonstration of the same −


 Live Demo

from collections import Counter
def make_string(str_1,str_2):
   dict_one = Counter(str_1)
   dict_two = Counter(str_2)

   result = dict_one & dict_two

   return result == dict_one

string_1 = 'Hi Mark'
string_2 = 'how are yoU'
print("The first string is :")
print("The second string is :")
if (make_string(string_1,string_2)==True):
   print("It is possible")
   print("It is not possible")


The first string is :
Hi Mark
The second string is :
how are yoU
It is not possible


  • The required packages are imported.

  • A method is defined, that takes two strings, and converts them into a counter.

  • It is then assigned to a dictionary.

  • Outside the dictionary, two strings are defined, and the method is called by passing these two strings.

  • The relevant output depending on whether the function returns ‘True’ or ‘False’ is shown on console.