Python | The appearance of an item in the dictionary of list values



Method # 1: Using vocabulary comprehension + sum()
This task can be accomplished using a combination of the above two utilities, in which we use vocabulary comprehension to link logic, and the sum function can be used to sum the matches found in the testlist.

# Python3 demo code
# Entering an element into a dictionary value list
# using a list comprehension + sum ()

 
# initializing dictionary

test_dict = { "Akshat" : [ 1 , < / code> 4 , 5 , 3 ],

"Nikhil" : [ 4 , 6 ],

  "Akash" : [ 5 , 2 , 1 ]}

 
# initialize the test list

test_list = [ 2 , 1 ]

 
# printing the original dict

print ( "The original dictionary:" + str (test_dict))

 
# print original list

print ( "The original list:" + str (test_list))

 
# using a list comprehension + sum ()
# Entering an element into a dictionary value list

res = {idx : sum ( 1 for i in j if i in test_list)

for idx, j in test_dict.items ()}

 
# print result

print ( "The summation of element occurrence:" + str (res))

Output:

 The original dictionary: {`Nikhil`: [4, 6],` Aksha t`: [1, 4, 5, 3], `Akash`: [5, 2, 1]} The original list: [2, 1] The summation of element occurrence: {` Nikhil`: 0, `Akshat` : 1, `Akash`: 2} 

Method # 2: Using collections.Counter()
Python suggests a built-in function that does the task of extracting the frequency and using that function and preparing to be present in the list of tests, we can solve the above problem with this function.

# Python3 demo code
# Entering an element into the list of dictionary values ​​
# using collection.Counter ()

from collections import Counter

 
# initializing dictionary

test_dict = { " Akshat " : [ 1 , 4 , 5 , 3 ],

"Nikhil" : [ 4 , 6 ],

"Akash" : [ 5 , 2 , 1 ]}

  
# initialize the test list

test_list = [ 2 , 1 ]

  
# printing the original dict

print ( "The original dictionary:" + str (test_dict))

 
# print original list

print ( "The original list:" + str (test_list))

  
# using collection.Counter ()
# Entering an element into the list of dictionary values
# skips the keyword of occurrence 0

res = dict (Counter (j for j in test_dict

for i in test_list if i in test_dict [j]))

 
# print result

print ( "The summation of element occurrence:" + str (res))

Output:

 The original dictionary: {`Nikhil`: [4, 6],` Akshat`: [1, 4, 5, 3], `Akash`: [5, 2, 1]} The original list: [2, 1] The summation of element occurrence: {`Akshat`: 1,` Akash`: 2}