HomeInterview QuestionsHow do you count the number of entries in a dictio…

How do you count the number of entries in a dictionary in Python?

🟢 Easy Conceptual Fresher level
2Times asked
Jul 2026Last seen
Jul 2026First seen

💡 Model Answer

Counting the number of entries in a Python dictionary is straightforward because dictionaries are built‑in data structures that keep track of their keys. The simplest way is to use the built‑in len() function: len(my_dict). This returns the number of key/value pairs, i.e., the number of entries. If you need to count only keys that satisfy a condition, you can use a generator expression: sum(1 for k in my_dict if condition(k)). For counting occurrences of a particular value, iterate over my_dict.values() and compare each value. Example: target = 5; count = sum(1 for v in my_dict.values() if v == target). All these operations run in O(n) time, where n is the number of keys, because Python dictionaries are hash tables and lookups are constant time on average. Using len() is the most efficient and idiomatic approach for a simple count. If you need to count the number of keys that map to a specific value, you can use collections.Counter on the values: from collections import Counter; counter = Counter(my_dict.values()); count = counter[target]. This also runs in O(n). For very large dictionaries, you might want to avoid creating intermediate lists; generator expressions are memory efficient. In summary, len(my_dict) gives the total number of entries; for conditional counts, use generator expressions or Counter. All operations are O(n) and use constant extra space aside from the dictionary itself.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500