
Python dictionary length - How to count all the elements in a dictionary
The len()
returns the number of items in a Python dictionary.
a = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}
b = {'book': 5, 'pen': 9}
len_a = len(a)
len_b = len(b)
print(len_a) # 3
print(len_b) # 2
It is a Python built-in function counting all objects in an iterable. Even if you write the comma after the last element, the length of the dictionary remains.
stocks = {'Apple': 114, 'Google': 1532, 'Facebook': 265, }
print(len(stocks)) # 3
A comma after the last element is called "trailing comma".
Length of a dictionary with a trailing comma and an empty dictionary
In Python, a dictionary can have a trailing comma and it's ignored to count elements. The length of an empty dictionary is 0.
d = {'book': 24, }
e = {}
print(len(d)) # 1
print(type(e)) # <class 'dict'>
print(len(e)) # 0
Comments
Powered by Markdown