Python - Count if dictionary position equals key or value
Last Updated :
27 Mar, 2023
Given a dictionary, count instances where dictionary item position equals key or value. Valid for Py >= 3.6 [ Introduction of dictionary ordering ].
Input : test_dict = {5:3, 2:3, 10:4, 7:3, 8:1, 9:5}
Output : 2
Explanation : At 3 and 5th position, values are 3 and 5.
Input : test_dict = {5:3, 2:3, 10:4, 8:1, 9:5}
Output : 1
Explanation : At 5th position, value is 5.
Method #1 : Using loop
In this we iterate for each dictionary item and test for each item to check if any position is equal to key or value of dictionary, if found, we iterate the counter.
Python3
# Python3 code to demonstrate working of
# Count if dictionary position equals key or value
# Using loop
# initializing dictionary
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
res = 0
test_dict = list(test_dict.items())
for idx in range(0, len(test_dict)):
# checking for key or value equality
if idx == test_dict[idx][0] or idx == test_dict[idx][1]:
res += 1
# printing result
print("The required frequency : " + str(res))
OutputThe original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required frequency : 3
Method #2 : Using sum() + list comprehension
In this, we assign 1 to each case in which dictionary index is found equal to any of its items, then perform list summation using sum().
Python3
# Python3 code to demonstrate working of
# Count if dictionary position equals key or value
# Using sum() + list comprehension
# initializing dictionary
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
test_dict = list(test_dict.items())
# sum() computing sum for filtered cases
res = sum([1 for idx in range(0, len(test_dict)) if idx ==
test_dict[idx][0] or idx == test_dict[idx][1]])
# printing result
print("The required frequency : " + str(res))
OutputThe original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required frequency : 3
Method #3: Using filter() and lambda function
Approach:
- Initialize a dictionary test_dict.
- Initialize a variable res to 0.
- Use a list comprehension to iterate over the enumerated items of the dictionary test_dict.items().
- For each enumerated key-value pair, check if the index i is present in the key-value pair.
- If the index i is present in the key-value pair, add 1 to the res variable.
- Print the resulting frequency of indices that match a key or a value in test_dict.
Python3
# initializing dictionary
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using enumerate() function
res = sum([1 for i, kv in enumerate(test_dict.items()) if i in kv])
# printing result
print("The required frequency : " + str(res))
OutputThe original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required frequency : 3
Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary Space: O(1), as we use only a constant amount of memory.
Similar Reads
Python | Count keys with particular value in dictionary Sometimes, while working with Python dictionaries, we can come across a problem in which we have a particular value, and we need to find frequency if it's occurrence. Let's discuss certain ways in which this problem can be solved. Method #1: Using loop This problem can be solved using naive method o
5 min read
Check if Value Exists in Python Dictionary We are given a dictionary and our task is to check whether a specific value exists in it or not. For example, if we have d = {'a': 1, 'b': 2, 'c': 3} and we want to check if the value 2 exists, the output should be True. Let's explore different ways to perform this check in Python.Naive ApproachThis
2 min read
Python - Test if custom keys equal to K in dictionary Given dictionary and custom keys list, check if all those custom keys equals K. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 10, "Geeks" : 10}, cust_keys = ["is", "for", "Geeks"], K = 10 Output : False Explanation : "is" is having 8 as value not 10, hence False Input : test_dict =
6 min read
Count the Key from Nested Dictionary in Python In Python, counting the occurrences of keys within a nested dictionary often requires traversing through its complex structure. In this article, we will see how to count the key from the nested dictionary in Python. Count the Key from the Nested Dictionary in PythonBelow are some ways and examples b
4 min read
Python - Associated Values Frequencies in Dictionary Sometimes, while working with dictionaries, we can have problem in which we need to compute the values associated to each value in dictionary in records list. This kind of problem is peculiar, but can have application in development domains. Lets discuss certain way in which this task can be perform
5 min read