Python Dictionary len function is used to return the dictionary length (the total key-value pairs). In this section, we discuss how to use this Python Dictionary len function, and the syntax behind this is:
len(dictionary_name)
Python Dictionary len Example
The Python dictionary len function returns the length of a dictionary. The below Python code prints the myDict length.
myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'} print("Dictionary Items: ", myDict) # Dict length print("\nThe Dictionary length : ", len(myDict))
In this program, we are going to insert a new value to a Dictionary and check the length. Next, we updated a value and displayed the length.
myDict = {'name': 'Kevin', 'age': 25} # Print Total Items print("Items : ", myDict) print("The length : ", len(myDict)) # Add an Item myDict['job'] = 'Programmer' print("\nItems : ", myDict) print("The length : ", len(myDict)) # Update an Item myDict['name'] = 'Python' print("\nItems : ", myDict) print("The length : ", len(myDict))
Items : {'name': 'Kevin', 'age': 25}
The length : 2
Items : {'name': 'Kevin', 'age': 25, 'job': 'Programmer'}
The length : 3
Items : {'name': 'Python', 'age': 25, 'job': 'Programmer'}
The length : 3