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
def main():
dict1 = { 'a' :[ 1 , 2 , 3 ],
'b' 🙁 1 , 2 , 3 ),
'c' : 5 ,
'd' : "nopqrs" ,
'e' :[ "A" , "B" , "C" ]}
count = 0
for k in dict1:
if isinstance (dict1[k], int ):
count + = 1
elif isinstance (dict1[k], str ):
count + = 1
else :
count + = len (dict1[k])
print ( "The total length of value is:" , count)
if __name__ = = '__main__' :
main()
|
Output:
The total length of value is: 11
Example :2
def main():
dict1 = { 'A' : "abcd" ,
'B' : set ([ 1 , 2 , 3 ]),
'C' 🙁 12 , "number" ),
'D' :[ 1 , 2 , 4 , 5 , 5 , 5 ]}
dict2 = {}
for k in dict1:
if isinstance (dict1[k], int ):
dict2[k] = 1
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' ])
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
def main():
dict1 = { 'a' :[ 1 , 2 , 3 ],
'b' 🙁 1 , 2 , 3 ),
'c' : 5 ,
'd' : "nopqrs" ,
'e' :[ "A" , "B" , "C" ]}
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)
if __name__ = = '__main__' :
main()
|
Output:
The total length of values is: 11
Method #3 Using dictionary Comprehension
def main():
dict1 = { 'A' : "abcd" ,
'B' : set ([ 1 , 2 , 3 ]),
'C' : ( 12 , "number" ),
'D' : [ 1 , 2 , 4 , 5 , 5 , 5 ]}
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' ])
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
def main():
dict1 = { 'a' :[ 1 , 2 , 3 ],
'b' 🙁 1 , 2 , 3 ),
'c' : 5 ,
'd' : "nopqrs" ,
'e' :[ "A" , "B" , "C" ]}
count = 0
for key, val in dict1.items():
if isinstance (val, int ):
count + = 1
elif isinstance (val, str ):
count + = 1
else :
count + = len (val)
print ( "The total length of value is:" , count)
if __name__ = = '__main__' :
main()
|
Output:
The total length of values is: 11
Example :2
def main():
dict1 = { 'A' : "abcd" ,
'B' : set ([ 1 , 2 , 3 ]),
'C' : ( 12 , "number" ),
'D' : [ 1 , 2 , 4 , 5 , 5 , 5 ]}
dict2 = {}
for key, val in dict1.items():
if isinstance (val, int ):
dict2[key] = 1
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' ])
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
def main():
dict1 = { 'a' :[ 1 , 2 , 3 ],
'b' 🙁 1 , 2 , 3 ),
'c' : 5 ,
'd' : "nopqrs" ,
'e' :[ "A" , "B" , "C" ]}
count = 0
for k in enumerate (dict1.items()):
if isinstance (k[ 1 ][ 1 ], int ):
count + = 1
elif isinstance (k[ 1 ][ 1 ], str ):
count + = 1
else :
count + = len (k[ 1 ][ 1 ])
print ( "The total length of value is:" , count)
if __name__ = = '__main__' :
main()
|
Output:
The total length of value is: 11
Example :2
def main():
dict1 = { 'A' : "abcd" ,
'B' : set ([ 1 , 2 , 3 ]),
'C' : ( 12 , "number" ),
'D' : [ 1 , 2 , 4 , 5 , 5 , 5 ]}
dict2 = {}
for k in enumerate (dict1.items()):
if isinstance (k[ 1 ][ 1 ], int ):
dict2[k[ 1 ][ 0 ]] = 1
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' ])
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...