Dictionary Methods in Python (cmp(), len(), items()...)

Dictionary in Python is one of the most frequently used collection data types. It is represented by key-value pairs where keys are indexed but values may not be. There are many Python built-in functions that make using dictionaries very easy in various Python programs. In this topic we will see three built-in methods: cmp(), len(), and items().

cmp() Method

The cmp() method compares two dictionaries based on keys and values. It is helpful in identifying duplicate dictionaries as well as doing relational comparisons among dictionaries. Note: This method is only available in Python 2 and has been removed in Python 3.

Syntax

cmp(dict1, dict2)

Where dict1 and dict2 are the two input dictionaries.

The method returns:

  • 0 if both dictionaries are equal
  • 1 if the first dictionary is greater
  • -1 if the first dictionary is smaller

Example

# Python 2 only - not available in Python 3
dict1 = {'Place': 'Delhi', 'distance': 137}
dict2 = {'Place': 'Agra', 'distance': 41}
dict3 = {'Place': 'Bangaluru', 'distance': 1100}
dict4 = {'Place': 'Bangaluru', 'distance': 1100}

print("comparison Result : %d" % cmp(dict1, dict2))
print("comparison Result : %d" % cmp(dict2, dict3))
print("comparison Result : %d" % cmp(dict3, dict4))
comparison Result : 1
comparison Result : -1
comparison Result : 0

len() Method

This method returns the total length of the dictionary, which equals the number of key-value pairs (items) in the dictionary.

Syntax

len(dict)

Example

dict1 = {'Place': 'Delhi', 'distance': 137}
dict2 = {'Place': 'Agra', 'distance': 41, 'Temp': 25}

print("Length of dict1:", len(dict1))
print("Length of dict2:", len(dict2))
Length of dict1: 2
Length of dict2: 3

dict.items() Method

The items() method returns a view object containing the dictionary's key-value pairs as tuples. This is useful when you need to iterate over both keys and values simultaneously.

Syntax

dictionary_name.items()

Example

dict1 = {'Place': 'Delhi', 'distance': 137}
dict2 = {'Place': 'Agra', 'distance': 41, 'Temp': 25}

print("Items in dict1:", dict1.items())
print("Items in dict2:", dict2.items())
Items in dict1: dict_items([('Place', 'Delhi'), ('distance', 137)])
Items in dict2: dict_items([('Place', 'Agra'), ('distance', 41), ('Temp', 25)])

Iterating with items()

You can iterate through dictionary items using a for loop ?

student = {'name': 'Alice', 'grade': 85, 'subject': 'Math'}

for key, value in student.items():
    print(f"{key}: {value}")
name: Alice
grade: 85
subject: Math

Conclusion

The len() method helps determine dictionary size, while items() provides key-value pairs for iteration. Note that cmp() is only available in Python 2 and has been removed from Python 3.

Updated on: 2026-03-15T17:12:50+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements