How to find length of dictionary values?
Last Updated :
10 May, 2020
In Python,
Dictionary is a collection of unordered data values. Dictionaries are also changeable and indexed. Dictionary holds key:value pair and they are written inside curly brackets. Each
key:value pair maps the key to its associated value.
Here we use
isinstance() method to check the type of the value whether it is a list, int, str, tuple, etc.
isinstance()
method which is an inbuilt method in Python. It returns a boolean if the object passed is an instance of the given class or not.
Let's discuss different methods to find the length of dictionary values.
Note: In the below methods the length of the string value is takes as one.
Method #1 Using in operator
Example: 1
Python3 1==
# Python program to find the
# length of dictionary values
def main():
# Defining the dictionary
dict1 = {'a':[1, 2, 3],
'b':(1, 2, 3),
'c':5,
'd':"nopqrs",
'e':["A", "B", "C"]}
# Initialize count
count = 0
# using in operator
for k in dict1:
# Check the type of value
# is int or not
if isinstance(dict1[k], int):
count += 1
# Check the type of value
# is str or not
elif isinstance(dict1[k], str):
count += 1
else:
count += len(dict1[k])
print("The total length of value is:", count)
# Driver Code
if __name__ == '__main__':
main()
Output:
The total length of value is: 11
Example :2
Python3 1==
# Python program to find the
# length of dictionary values
def main():
# Defining the dictionary
dict1 = {'A':"abcd",
'B':set([1, 2, 3]),
'C':(12, "number"),
'D':[1, 2, 4, 5, 5, 5]}
# Create a empty dictionary
dict2 = {}
# using in operator
for k in dict1:
# Check the type of value
# is int or not
if isinstance(dict1[k], int):
dict2[k] = 1
# Check the type of value
# is str or not
elif isinstance(dict1[k], str):
dict2[k] = 1
else:
dict2[k] = len(dict1[k])
print("The length of values associated\
with their keys are:", dict2)
print("The length of value associated\
with key 'B' is:", dict2['B'])
# Driver Code
if __name__ == '__main__':
main()
Output:
The length of values associated with their keys are: {'A': 1, 'B': 3, 'C': 2, 'D': 6}
The length of value associated with key 'B' is: 3
Method #2 Using list comprehension
Python3 1==
# Python program to find the
# length of dictionary values
def main():
# Defining the dictionary
dict1 = {'a':[1, 2, 3],
'b':(1, 2, 3),
'c':5,
'd':"nopqrs",
'e':["A", "B", "C"]}
# using list comprehension
count = sum([1 if isinstance(dict1[k], (str, int))
else len(dict1[k])
for k in dict1])
print("The total length of values is:", count)
# Driver Code
if __name__ == '__main__':
main()
Output:
The total length of values is: 11
Method #3 Using dictionary Comprehension
Python3 1==
# Python program to find the
# length of dictionary values
def main():
# Defining the dictionary
dict1 = {'A': "abcd",
'B': set([1, 2, 3]),
'C': (12, "number"),
'D': [1, 2, 4, 5, 5, 5]}
# using dictionary comprehension
dict2 = {k:1 if isinstance(dict1[k], (str, int))
else len(dict1[k])
for k in dict1}
print("The length of values associated \
with their keys are:", dict2)
print("The length of value associated \
with key 'B' is:", dict2['B'])
# Driver Code
if __name__ == '__main__':
main()
Output:
The length of values associated with their keys are: {'A': 1, 'B': 3, 'C': 2, 'D': 6}
The length of value associated with key 'B' is: 3
Method #4 Using dict.items()
Example :1
Python3 1==
# Python program to find the
# length of dictionary values
def main():
# Defining the dictionary
dict1 = {'a':[1, 2, 3],
'b':(1, 2, 3),
'c':5,
'd':"nopqrs",
'e':["A", "B", "C"]}
# Initialize count
count = 0
# using dict.items()
for key, val in dict1.items():
# Check the type of value
# is int or not
if isinstance(val, int):
count += 1
# Check the type of value
# is str or not
elif isinstance(val, str):
count += 1
else:
count += len(val)
print("The total length of value is:", count)
# Driver code
if __name__ == '__main__':
main()
Output:
The total length of values is: 11
Example :2
Python3 1==
# Python program to find the
# length of dictionary values
def main():
# Defining the dictionary
dict1 = {'A': "abcd",
'B': set([1, 2, 3]),
'C': (12, "number"),
'D': [1, 2, 4, 5, 5, 5]}
# Create a empty dictionary
dict2 = {}
# using dict.items()
for key, val in dict1.items():
# Check the type of value
# is int or not
if isinstance(val, int):
dict2[key] = 1
# Check the type of value
# is str or not
elif isinstance(val, str):
dict2[key] = 1
else:
dict2[key] = len(val)
print("The length of values associated \
with their keys are:", dict2)
print("The length of value associated \
with key 'B' is:", dict2['B'])
# Driver Code
if __name__ == '__main__':
main()
Output:
The length of values associated with their keys are: {'A': 1, 'B': 3, 'C': 2, 'D': 6}
The length of value associated with key 'B' is: 3
Method #5 Using enumerate()
Example :1
Python3 1==
# Python program to find the
# length of dictionary values
def main():
# Defining the dictionary
dict1 = {'a':[1, 2, 3],
'b':(1, 2, 3),
'c':5,
'd':"nopqrs",
'e':["A", "B", "C"]}
# Initialize count
count = 0
# using enumerate()
for k in enumerate(dict1.items()):
# Check the type of value
# is int or not
if isinstance(k[1][1], int):
count += 1
# Check the type of value
# is str or not
elif isinstance(k[1][1], str):
count += 1
else:
count += len(k[1][1])
print("The total length of value is:", count)
# Driver Code
if __name__ == '__main__':
main()
Output:
The total length of value is: 11
Example :2
Python3 1==
# Python program to find the
# length of dictionary values
def main():
# Defining the dictionary
dict1 = {'A': "abcd",
'B': set([1, 2, 3]),
'C': (12, "number"),
'D': [1, 2, 4, 5, 5, 5]}
# Create a empty dictionary
dict2 = {}
# using enumerate()
for k in enumerate(dict1.items()):
# Check the type of value
# is int or not
if isinstance(k[1][1], int):
dict2[k[1][0]] = 1
# Check the type of value
# is str or not
elif isinstance(k[1][1], str):
dict2[k[1][0]] = 1
else:
dict2[k[1][0]] = len(k[1][1])
print("The length of values associated\
with their keys are:", dict2)
print("The length of value associated \
with key 'B' is:", dict2['B'])
# Driver Code
if __name__ == '__main__':
main()
Output:
The length of values associated with their keys are: {'A': 1, 'B': 3, 'C': 2, 'D': 6}
The length of value associated with key 'B' is: 3
Similar Reads
Get length of dictionary in Python Python provides multiple methods to get the length, and we can apply these methods to both simple and nested dictionaries. Letâs explore the various methods.Using Len() FunctionTo calculate the length of a dictionary, we can use Python built-in len() method. It method returns the number of keys in d
3 min read
Python - Frequencies of Values in a Dictionary Sometimes, while working with python dictionaries, we can have a problem in which we need to extract the frequency of values in the dictionary. This is quite a common problem and has applications in many domains including web development and day-day programming. Let's discuss certain ways in which t
4 min read
Python dictionary values() values() method in Python is used to obtain a view object that contains all the values in a dictionary. This view object is dynamic, meaning it updates automatically if the dictionary is modified. If we use the type() method on the return value, we get "dict_values object". It must be cast to obtain
2 min read
How to Find Length of a list in Python The length of a list means the number of elements it contains. In-Built len() function can be used to find the length of an object by passing the object within the parentheses. Here is the Python example to find the length of a list using len().Pythona1 = [10, 50, 30, 40] n = len(a1) print("Size of
2 min read
Python | Set 4 (Dictionary, Keywords in Python) In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value c
5 min read
Python | Find depth of a dictionary Prerequisite: Nested dictionary The task is to find the depth of given dictionary in Python. Let's discuss all different methods to do this task. Examples: Input : {1:'a', 2: {3: {4: {}}}} Output : 4 Input : {'a':1, 'b': {'c':'geek'}} Output : 3 Approach #1 : Naive Approach A naive approach in order
5 min read
Python Dictionary get() Method Python Dictionary get() Method returns the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument).Python Dictionary get() Method Syntax:Syntax : Dict.get(key, Value)Parameters: key: The key name of the item you want to return
3 min read
Python | Count number of items in a dictionary value that is a list In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a ke
5 min read
How to find size of an object in Python? In python, the usage of sys.getsizeof() can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes. It takes at most two arguments i.e Object itself. Note: Only the memory consumption directly attributed t
2 min read
Output of python program | Set 14 (Dictionary) Prerequisite: Dictionary Note: Output of all these programs is tested on Python31) What is the output of the following program? PYTHON3 D = dict() for x in enumerate(range(2)): D[x[0]] = x[1] D[x[1]+7] = x[0] print(D) a) KeyError b) {0: 1, 7: 0, 1: 1, 8: 0} c) {0: 0, 7: 0, 1: 1, 8: 1} d) {1: 1, 7: 2
3 min read